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.
19 #define VAR_SERVER 1 /* Should be in meshlink.conf */
20 #define VAR_HOST 2 /* Can be in host config file */
21 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
22 #define VAR_OBSOLETE 8 /* Should not be used anymore */
23 #define VAR_SAFE 16 /* Variable is safe when accepting invitations */
24 #define MAX_ADDRESS_LENGTH 45 /* Max length of an (IPv6) address */
25 #define MAX_PORT_LENGTH 5 /* 0-65535 */
37 #include "meshlink_internal.h"
46 #include "ed25519/sha512.h"
47 #include "discovery.h"
50 #define MSG_NOSIGNAL 0
53 __thread meshlink_errno_t meshlink_errno;
54 meshlink_log_cb_t global_log_cb;
55 meshlink_log_level_t global_log_level;
57 //TODO: this can go away completely
58 const var_t variables[] = {
59 /* Server configuration */
60 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
62 /* Host configuration */
63 {"SubMesh", VAR_HOST | VAR_SAFE},
64 {"CanonicalAddress", VAR_HOST},
65 {"Address", VAR_HOST | VAR_MULTIPLE},
66 {"ECDSAPublicKey", VAR_HOST},
71 static bool fcopy(FILE *out, const char *filename) {
72 FILE *in = fopen(filename, "r");
75 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
82 while((len = fread(buf, 1, sizeof(buf), in))) {
83 fwrite(buf, len, 1, out);
90 static int rstrip(char *value) {
91 int len = strlen(value);
93 while(len && strchr("\t\r\n ", value[len - 1])) {
100 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
103 if(!filename || (*hostname && *port)) {
107 FILE *f = fopen(filename, "r");
113 while(fgets(line, sizeof(line), f)) {
119 p += strcspn(p, "\t =");
125 q = p + strspn(p, "\t ");
128 q += 1 + strspn(q + 1, "\t ");
131 // q is now pointing to the hostname
133 p = q + strcspn(q, "\t ");
139 p += strspn(p, "\t ");
140 p[strcspn(p, "\t ")] = 0;
141 // p is now pointing to the port, if present
143 if(!*port && !strcasecmp(line, "Port")) {
145 } else if(!strcasecmp(line, "CanonicalAddress")) {
146 *hostname = xstrdup(q);
154 if(*hostname && *port) {
162 static bool is_valid_hostname(const char *hostname) {
167 for(const char *p = hostname; *p; p++) {
168 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
176 static bool is_valid_port(const char *port) {
183 unsigned long int result = strtoul(port, &end, 10);
184 return result && result < 65536 && !*end;
187 for(const char *p = port; *p; p++) {
188 if(!(isalnum(*p) || *p == '-')) {
196 static void set_timeout(int sock, int timeout) {
201 tv.tv_sec = timeout / 1000;
202 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
204 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
205 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
208 struct socket_in_netns_params {
216 static void *socket_in_netns_thread(void *arg) {
217 struct socket_in_netns_params *params = arg;
219 if(setns(params->netns, CLONE_NEWNET) == -1) {
220 meshlink_errno = MESHLINK_EINVAL;
222 params->fd = socket(params->domain, params->type, params->protocol);
228 static int socket_in_netns(int domain, int type, int protocol, int netns) {
230 return socket(domain, type, protocol);
233 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
237 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
238 pthread_join(thr, NULL);
244 // Find out what local address a socket would use if we connect to the given address.
245 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
246 // of both endpoints, but this will actually not send any UDP packet.
247 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
248 struct addrinfo *rai = NULL;
249 const struct addrinfo hint = {
250 .ai_family = AF_UNSPEC,
251 .ai_socktype = SOCK_DGRAM,
252 .ai_protocol = IPPROTO_UDP,
255 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
259 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
266 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
274 struct sockaddr_storage sn;
275 socklen_t sl = sizeof(sn);
277 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
284 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
291 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
292 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
295 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
296 char *hostname = NULL;
298 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
299 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
300 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
303 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
304 if(family != AF_UNSPEC && aip->ai_family != family) {
308 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
311 set_timeout(s, 5000);
313 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
320 send(s, request, sizeof(request) - 1, 0);
321 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
326 if(line[len - 1] == '\n') {
330 char *p = strrchr(line, '\n');
333 hostname = xstrdup(p + 1);
349 // Check that the hostname is reasonable
350 if(hostname && !is_valid_hostname(hostname)) {
356 meshlink_errno = MESHLINK_ERESOLV;
362 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
365 // Determine address of the local interface used for outgoing connections.
366 char localaddr[NI_MAXHOST];
367 bool success = false;
369 if(family == AF_INET) {
370 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
371 } else if(family == AF_INET6) {
372 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
376 meshlink_errno = MESHLINK_ENETWORK;
380 return xstrdup(localaddr);
383 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
384 for(int i = 0; i < n; i++) {
389 // Ignore duplicate hostnames
392 for(int j = 0; j < i; j++) {
397 if(strcmp(host[i], host[j])) {
401 if(strcmp(port[i], port[j])) {
419 // This gets the hostname part for use in invitation URLs
420 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
421 char *hostname[4] = {NULL};
422 char *port[4] = {NULL};
423 char *hostport = NULL;
425 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
426 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
429 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
430 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
433 // Add local addresses if requested
434 if(flags & MESHLINK_INVITE_LOCAL) {
435 if(flags & MESHLINK_INVITE_IPV4) {
436 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
439 if(flags & MESHLINK_INVITE_IPV6) {
440 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
444 // Add public/canonical addresses if requested
445 if(flags & MESHLINK_INVITE_PUBLIC) {
446 // Try the CanonicalAddress first
447 char filename[PATH_MAX] = "";
448 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
449 scan_for_canonical_address(filename, &hostname[2], &port[2]);
452 if(flags & MESHLINK_INVITE_IPV4) {
453 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
456 if(flags & MESHLINK_INVITE_IPV6) {
457 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
462 for(int i = 0; i < 4; i++) {
463 // Ensure we always have a port number
464 if(hostname[i] && !port[i]) {
465 port[i] = xstrdup(mesh->myport);
469 remove_duplicate_hostnames(hostname, port, 4);
471 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
472 for(int i = 0; i < 4; i++) {
477 // Convert what we have to a sockaddr
478 struct addrinfo *ai_in, *ai_out;
479 struct addrinfo hint = {
480 .ai_family = AF_UNSPEC,
481 .ai_flags = AI_NUMERICSERV,
482 .ai_socktype = SOCK_STREAM,
484 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
490 // Convert it to a hostname
491 char resolved_host[NI_MAXHOST];
492 char resolved_port[NI_MAXSERV];
493 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
500 // Convert the hostname back to a sockaddr
501 hint.ai_family = ai_in->ai_family;
502 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
509 // Check if it's still the same sockaddr
510 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
512 freeaddrinfo(ai_out);
516 // Yes: replace the hostname with the resolved one
518 hostname[i] = xstrdup(resolved_host);
521 freeaddrinfo(ai_out);
525 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
526 remove_duplicate_hostnames(hostname, port, 4);
528 // Concatenate all unique address to the hostport string
529 for(int i = 0; i < 4; i++) {
534 // Ensure we have the same addresses in our own host config file.
536 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
537 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
540 // Append the address to the hostport string
542 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
544 hostport = newhostport;
553 static char *get_line(const char **data) {
554 if(!data || !*data) {
563 static char line[1024];
564 const char *end = strchr(*data, '\n');
565 size_t len = end ? (size_t)(end - *data) : strlen(*data);
567 if(len >= sizeof(line)) {
568 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
572 if(len && !isprint(**data)) {
576 memcpy(line, *data, len);
588 static char *get_value(const char *data, const char *var) {
589 char *line = get_line(&data);
595 char *sep = line + strcspn(line, " \t=");
596 char *val = sep + strspn(sep, " \t");
599 val += 1 + strspn(val + 1, " \t");
604 if(strcasecmp(line, var)) {
611 static bool try_bind(int port) {
612 struct addrinfo *ai = NULL;
613 struct addrinfo hint = {
614 .ai_flags = AI_PASSIVE,
615 .ai_family = AF_UNSPEC,
616 .ai_socktype = SOCK_STREAM,
617 .ai_protocol = IPPROTO_TCP,
621 snprintf(portstr, sizeof(portstr), "%d", port);
623 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
628 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
635 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
650 int check_port(meshlink_handle_t *mesh) {
651 for(int i = 0; i < 1000; i++) {
652 int port = 0x1000 + (rand() & 0x7fff);
655 char filename[PATH_MAX];
656 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
657 FILE *f = fopen(filename, "a");
660 meshlink_errno = MESHLINK_ESTORAGE;
661 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
665 fprintf(f, "Port = %d\n", port);
671 meshlink_errno = MESHLINK_ENETWORK;
672 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
676 static void deltree(const char *dirname) {
677 DIR *d = opendir(dirname);
682 while((ent = readdir(d))) {
683 if(ent->d_name[0] == '.') {
687 char filename[PATH_MAX];
688 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
690 if(unlink(filename)) {
701 static bool finalize_join(meshlink_handle_t *mesh) {
702 char *name = xstrdup(get_value(mesh->data, "Name"));
705 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
709 if(!check_id(name)) {
710 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
714 char filename[PATH_MAX];
715 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
717 FILE *f = fopen(filename, "w");
720 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
724 fprintf(f, "Name = %s\n", name);
726 // Wipe all old host config files and invitations
727 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
730 if(mkdir(filename, 0777) && errno != EEXIST) {
731 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
735 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
738 // Create a new host config file for ourself
739 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
740 FILE *fh = fopen(filename, "w");
743 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
748 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
749 // Other chunks go unfiltered to their respective host config files
750 const char *p = mesh->data;
753 while((l = get_line(&p))) {
759 // Split line into variable and value
760 int len = strcspn(l, "\t =");
762 value += strspn(value, "\t ");
766 value += strspn(value, "\t ");
772 if(!strcasecmp(l, "Name"))
773 if(strcmp(value, name)) {
777 } else if(!strcasecmp(l, "NetName")) {
781 // Check the list of known variables
785 for(i = 0; variables[i].name; i++) {
786 if(strcasecmp(l, variables[i].name)) {
794 // Ignore unknown and unsafe variables
796 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
798 } else if(!(variables[i].type & VAR_SAFE)) {
799 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
803 // Copy the safe variable to the right config file
804 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
809 while(l && !strcasecmp(l, "Name")) {
810 if(!check_id(value)) {
811 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
815 if(!strcmp(value, name)) {
816 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
820 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
821 f = fopen(filename, "w");
824 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
828 while((l = get_line(&p))) {
829 if(!strcmp(l, "#---------------------------------------------------------------#")) {
833 int len = strcspn(l, "\t =");
835 if(len == 4 && !strncasecmp(l, "Name", 4)) {
837 value += strspn(value, "\t ");
841 value += strspn(value, "\t ");
855 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
862 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
863 fprintf(fh, "Port = %s\n", mesh->myport);
867 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
871 free(mesh->self->name);
872 free(mesh->self->connection->name);
873 mesh->name = xstrdup(name);
874 mesh->self->name = xstrdup(name);
875 mesh->self->connection->name = name;
877 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
879 load_all_nodes(mesh);
884 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
886 meshlink_handle_t *mesh = handle;
887 const char *ptr = data;
890 int result = send(mesh->sock, ptr, len, 0);
892 if(result == -1 && errno == EINTR) {
894 } else if(result <= 0) {
905 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
906 meshlink_handle_t *mesh = handle;
909 case SPTPS_HANDSHAKE:
910 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
913 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
914 memcpy(mesh->data + mesh->thedatalen, msg, len);
915 mesh->thedatalen += len;
916 mesh->data[mesh->thedatalen] = 0;
920 mesh->thedatalen = 0;
921 return finalize_join(mesh);
924 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
925 shutdown(mesh->sock, SHUT_RDWR);
926 mesh->success = true;
936 static bool recvline(meshlink_handle_t *mesh, size_t len) {
937 char *newline = NULL;
943 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
944 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
946 if(result == -1 && errno == EINTR) {
948 } else if(result <= 0) {
952 mesh->blen += result;
955 if((size_t)(newline - mesh->buffer) >= len) {
959 len = newline - mesh->buffer;
961 memcpy(mesh->line, mesh->buffer, len);
963 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
964 mesh->blen -= len + 1;
968 static bool sendline(int fd, char *format, ...) {
969 static char buffer[4096];
974 va_start(ap, format);
975 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
978 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
986 int result = send(fd, p, blen, MSG_NOSIGNAL);
988 if(result == -1 && errno == EINTR) {
990 } else if(result <= 0) {
1001 static const char *errstr[] = {
1002 [MESHLINK_OK] = "No error",
1003 [MESHLINK_EINVAL] = "Invalid argument",
1004 [MESHLINK_ENOMEM] = "Out of memory",
1005 [MESHLINK_ENOENT] = "No such node",
1006 [MESHLINK_EEXIST] = "Node already exists",
1007 [MESHLINK_EINTERNAL] = "Internal error",
1008 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1009 [MESHLINK_ESTORAGE] = "Storage error",
1010 [MESHLINK_ENETWORK] = "Network error",
1011 [MESHLINK_EPEER] = "Error communicating with peer",
1012 [MESHLINK_ENOTSUP] = "Operation not supported",
1013 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1016 const char *meshlink_strerror(meshlink_errno_t err) {
1017 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1018 return "Invalid error code";
1024 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1027 char pubname[PATH_MAX], privname[PATH_MAX];
1029 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1031 if(!(key = ecdsa_generate())) {
1032 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1033 meshlink_errno = MESHLINK_EINTERNAL;
1036 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1039 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1040 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1041 meshlink_errno = MESHLINK_ESTORAGE;
1045 f = fopen(privname, "wb");
1048 meshlink_errno = MESHLINK_ESTORAGE;
1053 fchmod(fileno(f), 0600);
1056 if(!ecdsa_write_pem_private_key(key, f)) {
1057 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1060 meshlink_errno = MESHLINK_EINTERNAL;
1066 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1067 f = fopen(pubname, "a");
1070 meshlink_errno = MESHLINK_ESTORAGE;
1074 char *pubkey = ecdsa_get_base64_public_key(key);
1075 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1084 static struct timeval idle(event_loop_t *loop, void *data) {
1086 meshlink_handle_t *mesh = data;
1087 struct timeval t, tmin = {3600, 0};
1089 for splay_each(node_t, n, mesh->nodes) {
1094 t = utcp_timeout(n->utcp);
1096 if(timercmp(&t, &tmin, <)) {
1104 // Get our local address(es) by simulating connecting to an Internet host.
1105 static void add_local_addresses(meshlink_handle_t *mesh) {
1106 char host[NI_MAXHOST];
1107 char entry[MAX_STRING_SIZE];
1111 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1112 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1113 append_config_file(mesh, mesh->name, "Address", entry);
1118 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1119 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1120 append_config_file(mesh, mesh->name, "Address", entry);
1124 static bool meshlink_setup(meshlink_handle_t *mesh) {
1125 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1126 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1127 meshlink_errno = MESHLINK_ESTORAGE;
1131 char filename[PATH_MAX];
1132 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1134 if(mkdir(filename, 0777) && errno != EEXIST) {
1135 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1136 meshlink_errno = MESHLINK_ESTORAGE;
1140 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1142 if(!access(filename, F_OK)) {
1143 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1144 meshlink_errno = MESHLINK_EEXIST;
1148 FILE *f = fopen(filename, "w");
1151 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1152 meshlink_errno = MESHLINK_ESTORAGE;
1156 fprintf(f, "Name = %s\n", mesh->name);
1159 if(!ecdsa_keygen(mesh)) {
1160 meshlink_errno = MESHLINK_EINTERNAL;
1165 if(check_port(mesh) == 0) {
1166 meshlink_errno = MESHLINK_ENETWORK;
1174 static void *setup_network_in_netns_thread(void *arg) {
1175 meshlink_handle_t *mesh = arg;
1177 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1181 bool success = setup_network(mesh);
1182 add_local_addresses(mesh);
1183 return success ? arg : NULL;
1186 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1187 if(!confbase || !*confbase) {
1188 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1189 meshlink_errno = MESHLINK_EINVAL;
1193 if(!appname || !*appname) {
1194 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1195 meshlink_errno = MESHLINK_EINVAL;
1199 if(strchr(appname, ' ')) {
1200 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1201 meshlink_errno = MESHLINK_EINVAL;
1205 if(!name || !*name) {
1206 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1208 } else { //check name only if there is a name != NULL
1209 if(!check_id(name)) {
1210 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1211 meshlink_errno = MESHLINK_EINVAL;
1216 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1217 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1218 meshlink_errno = MESHLINK_EINVAL;
1222 meshlink_open_params_t *params = xzalloc(sizeof * params);
1224 params->confbase = xstrdup(confbase);
1225 params->name = xstrdup(name);
1226 params->appname = xstrdup(appname);
1227 params->devclass = devclass;
1233 void meshlink_open_params_free(meshlink_open_params_t *params) {
1235 meshlink_errno = MESHLINK_EINVAL;
1239 free(params->confbase);
1241 free(params->appname);
1246 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1247 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1248 meshlink_open_params_t params = {NULL};
1250 params.confbase = (char *)confbase;
1251 params.name = (char *)name;
1252 params.appname = (char *)appname;
1253 params.devclass = devclass;
1256 return meshlink_open_ex(¶ms);
1258 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1259 // Validate arguments provided by the application
1260 bool usingname = false;
1262 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1264 if(!params->confbase || !*params->confbase) {
1265 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1266 meshlink_errno = MESHLINK_EINVAL;
1270 if(!params->appname || !*params->appname) {
1271 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1272 meshlink_errno = MESHLINK_EINVAL;
1276 if(strchr(params->appname, ' ')) {
1277 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1278 meshlink_errno = MESHLINK_EINVAL;
1282 if(!params->name || !*params->name) {
1283 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1285 } else { //check name only if there is a name != NULL
1287 if(!check_id(params->name)) {
1288 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1289 meshlink_errno = MESHLINK_EINVAL;
1296 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1297 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1298 meshlink_errno = MESHLINK_EINVAL;
1302 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1303 mesh->confbase = xstrdup(params->confbase);
1304 mesh->appname = xstrdup(params->appname);
1305 mesh->devclass = params->devclass;
1306 mesh->discovery = true;
1307 mesh->invitation_timeout = 604800; // 1 week
1308 mesh->netns = params->netns;
1309 mesh->submeshes = NULL;
1312 mesh->name = xstrdup(params->name);
1316 pthread_mutexattr_t attr;
1317 pthread_mutexattr_init(&attr);
1318 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1319 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1321 mesh->threadstarted = false;
1322 event_loop_init(&mesh->loop);
1323 mesh->loop.data = mesh;
1325 meshlink_queue_init(&mesh->outpacketqueue);
1327 // Check whether meshlink.conf already exists
1329 char filename[PATH_MAX];
1330 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1332 if(access(filename, R_OK)) {
1333 if(errno == ENOENT) {
1334 // If not, create it
1335 if(!meshlink_setup(mesh)) {
1336 // meshlink_errno is set by meshlink_setup()
1340 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1341 meshlink_close(mesh);
1342 meshlink_errno = MESHLINK_ESTORAGE;
1347 // Open the configuration file and lock it
1349 mesh->conffile = fopen(filename, "r");
1351 if(!mesh->conffile) {
1352 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1353 meshlink_close(mesh);
1354 meshlink_errno = MESHLINK_ESTORAGE;
1359 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1363 // TODO: use _locking()?
1366 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1367 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1368 meshlink_close(mesh);
1369 meshlink_errno = MESHLINK_EBUSY;
1375 // Read the configuration
1377 init_configuration(&mesh->config);
1379 if(!read_server_config(mesh)) {
1380 meshlink_close(mesh);
1381 meshlink_errno = MESHLINK_ESTORAGE;
1386 struct WSAData wsa_state;
1388 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1392 // Setup up everything
1393 // TODO: we should not open listening sockets yet
1395 bool success = false;
1397 if(mesh->netns != -1) {
1400 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1401 void *retval = NULL;
1402 success = pthread_join(thr, &retval) == 0 && retval;
1405 success = setup_network(mesh);
1406 add_local_addresses(mesh);
1410 meshlink_close(mesh);
1411 meshlink_errno = MESHLINK_ENETWORK;
1415 idle_set(&mesh->loop, idle, mesh);
1417 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1421 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1422 meshlink_submesh_t *s = NULL;
1425 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1426 meshlink_errno = MESHLINK_EINVAL;
1430 if(!submesh || !*submesh) {
1431 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1432 meshlink_errno = MESHLINK_EINVAL;
1436 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh);
1439 logger(NULL, MESHLINK_ERROR, "SubMesh Already exists!\n");
1440 meshlink_errno = MESHLINK_EEXIST;
1444 s = (meshlink_submesh_t *)new_submesh();
1445 s->name = xstrdup(submesh);
1447 submesh_add(mesh, (submesh_t *)s);
1449 meshlink_errno = MESHLINK_OK;
1453 static void *meshlink_main_loop(void *arg) {
1454 meshlink_handle_t *mesh = arg;
1456 if(mesh->netns != -1) {
1457 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1462 pthread_mutex_lock(&(mesh->mesh_mutex));
1464 try_outgoing_connections(mesh);
1466 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1468 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1470 pthread_mutex_unlock(&(mesh->mesh_mutex));
1474 bool meshlink_start(meshlink_handle_t *mesh) {
1476 meshlink_errno = MESHLINK_EINVAL;
1480 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1482 pthread_mutex_lock(&(mesh->mesh_mutex));
1484 if(mesh->threadstarted) {
1485 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1486 pthread_mutex_unlock(&(mesh->mesh_mutex));
1490 if(mesh->listen_socket[0].tcp.fd < 0) {
1491 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1492 meshlink_errno = MESHLINK_ENETWORK;
1496 mesh->thedatalen = 0;
1498 // TODO: open listening sockets first
1500 //Check that a valid name is set
1502 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1503 meshlink_errno = MESHLINK_EINVAL;
1504 pthread_mutex_unlock(&(mesh->mesh_mutex));
1508 // Start the main thread
1510 event_loop_start(&mesh->loop);
1512 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1513 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1514 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1515 meshlink_errno = MESHLINK_EINTERNAL;
1516 event_loop_stop(&mesh->loop);
1517 pthread_mutex_unlock(&(mesh->mesh_mutex));
1521 mesh->threadstarted = true;
1525 if(mesh->discovery) {
1526 discovery_start(mesh);
1531 pthread_mutex_unlock(&(mesh->mesh_mutex));
1535 void meshlink_stop(meshlink_handle_t *mesh) {
1537 meshlink_errno = MESHLINK_EINVAL;
1541 pthread_mutex_lock(&(mesh->mesh_mutex));
1542 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1547 if(mesh->discovery) {
1548 discovery_stop(mesh);
1553 // Shut down the main thread
1554 event_loop_stop(&mesh->loop);
1556 // Send ourselves a UDP packet to kick the event loop
1557 for(int i = 0; i < mesh->listen_sockets; i++) {
1559 socklen_t salen = sizeof(sa.sa);
1561 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1562 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1566 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1567 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1571 if(mesh->threadstarted) {
1572 // Wait for the main thread to finish
1573 pthread_mutex_unlock(&(mesh->mesh_mutex));
1574 pthread_join(mesh->thread, NULL);
1575 pthread_mutex_lock(&(mesh->mesh_mutex));
1577 mesh->threadstarted = false;
1580 // Close all metaconnections
1581 if(mesh->connections) {
1582 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1584 connection_t *c = node->data;
1586 terminate_connection(mesh, c, false);
1590 if(mesh->outgoings) {
1591 list_delete_list(mesh->outgoings);
1592 mesh->outgoings = NULL;
1595 pthread_mutex_unlock(&(mesh->mesh_mutex));
1598 void meshlink_close(meshlink_handle_t *mesh) {
1599 if(!mesh || !mesh->confbase) {
1600 meshlink_errno = MESHLINK_EINVAL;
1604 // stop can be called even if mesh has not been started
1605 meshlink_stop(mesh);
1607 // lock is not released after this
1608 pthread_mutex_lock(&(mesh->mesh_mutex));
1610 // Close and free all resources used.
1612 close_network_connections(mesh);
1614 logger(mesh, MESHLINK_INFO, "Terminating");
1616 exit_configuration(&mesh->config);
1617 event_loop_exit(&mesh->loop);
1621 if(mesh->confbase) {
1627 ecdsa_free(mesh->invitation_key);
1629 if(mesh->netns != -1) {
1634 free(mesh->appname);
1635 free(mesh->confbase);
1636 pthread_mutex_destroy(&(mesh->mesh_mutex));
1638 if(mesh->conffile) {
1639 fclose(mesh->conffile);
1642 memset(mesh, 0, sizeof(*mesh));
1647 bool meshlink_destroy(const char *confbase) {
1649 meshlink_errno = MESHLINK_EINVAL;
1653 char filename[PATH_MAX];
1654 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1656 if(unlink(filename)) {
1657 if(errno == ENOENT) {
1658 meshlink_errno = MESHLINK_ENOENT;
1661 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1662 meshlink_errno = MESHLINK_ESTORAGE;
1672 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1674 meshlink_errno = MESHLINK_EINVAL;
1678 pthread_mutex_lock(&(mesh->mesh_mutex));
1679 mesh->receive_cb = cb;
1680 pthread_mutex_unlock(&(mesh->mesh_mutex));
1683 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1685 meshlink_errno = MESHLINK_EINVAL;
1689 pthread_mutex_lock(&(mesh->mesh_mutex));
1690 mesh->node_status_cb = cb;
1691 pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1696 meshlink_errno = MESHLINK_EINVAL;
1700 pthread_mutex_lock(&(mesh->mesh_mutex));
1701 mesh->node_duplicate_cb = cb;
1702 pthread_mutex_unlock(&(mesh->mesh_mutex));
1705 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1707 pthread_mutex_lock(&(mesh->mesh_mutex));
1709 mesh->log_level = cb ? level : 0;
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1713 global_log_level = cb ? level : 0;
1717 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1718 meshlink_packethdr_t *hdr;
1720 // Validate arguments
1721 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1722 meshlink_errno = MESHLINK_EINVAL;
1731 meshlink_errno = MESHLINK_EINVAL;
1735 // Prepare the packet
1736 vpn_packet_t *packet = malloc(sizeof(*packet));
1739 meshlink_errno = MESHLINK_ENOMEM;
1743 packet->probe = false;
1744 packet->tcp = false;
1745 packet->len = len + sizeof(*hdr);
1747 hdr = (meshlink_packethdr_t *)packet->data;
1748 memset(hdr, 0, sizeof(*hdr));
1749 // leave the last byte as 0 to make sure strings are always
1750 // null-terminated if they are longer than the buffer
1751 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1752 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1754 memcpy(packet->data + sizeof(*hdr), data, len);
1757 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1759 meshlink_errno = MESHLINK_ENOMEM;
1763 // Notify event loop
1764 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1769 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1771 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1777 mesh->self->in_packets++;
1778 mesh->self->in_bytes += packet->len;
1779 route(mesh, mesh->self, packet);
1782 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1783 if(!mesh || !destination) {
1784 meshlink_errno = MESHLINK_EINVAL;
1788 pthread_mutex_lock(&(mesh->mesh_mutex));
1790 node_t *n = (node_t *)destination;
1792 if(!n->status.reachable) {
1793 pthread_mutex_unlock(&(mesh->mesh_mutex));
1796 } else if(n->mtuprobes > 30 && n->minmtu) {
1797 pthread_mutex_unlock(&(mesh->mesh_mutex));
1800 pthread_mutex_unlock(&(mesh->mesh_mutex));
1805 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1806 if(!mesh || !node) {
1807 meshlink_errno = MESHLINK_EINVAL;
1811 pthread_mutex_lock(&(mesh->mesh_mutex));
1813 node_t *n = (node_t *)node;
1815 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1816 meshlink_errno = MESHLINK_EINTERNAL;
1817 pthread_mutex_unlock(&(mesh->mesh_mutex));
1821 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1824 meshlink_errno = MESHLINK_EINTERNAL;
1827 pthread_mutex_unlock(&(mesh->mesh_mutex));
1831 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1833 meshlink_errno = MESHLINK_EINVAL;
1837 return (meshlink_node_t *)mesh->self;
1840 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1841 if(!mesh || !name) {
1842 meshlink_errno = MESHLINK_EINVAL;
1846 meshlink_node_t *node = NULL;
1848 pthread_mutex_lock(&(mesh->mesh_mutex));
1849 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1850 pthread_mutex_unlock(&(mesh->mesh_mutex));
1854 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1855 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1856 meshlink_errno = MESHLINK_EINVAL;
1860 meshlink_node_t **result;
1863 pthread_mutex_lock(&(mesh->mesh_mutex));
1865 *nmemb = mesh->nodes->count;
1866 result = realloc(nodes, *nmemb * sizeof(*nodes));
1869 meshlink_node_t **p = result;
1871 for splay_each(node_t, n, mesh->nodes) {
1872 *p++ = (meshlink_node_t *)n;
1877 meshlink_errno = MESHLINK_ENOMEM;
1880 pthread_mutex_unlock(&(mesh->mesh_mutex));
1885 meshlink_node_t **meshlink_get_all_nodes_by_dev_class(meshlink_handle_t *mesh, dev_class_t devclass, meshlink_node_t **nodes, size_t *nmemb) {
1886 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1887 meshlink_errno = MESHLINK_EINVAL;
1891 meshlink_node_t **result;
1893 pthread_mutex_lock(&(mesh->mesh_mutex));
1897 for splay_each(node_t, n, mesh->nodes) {
1898 if(n->devclass == devclass) {
1899 *nmemb = *nmemb + 1;
1905 pthread_mutex_unlock(&(mesh->mesh_mutex));
1909 result = realloc(nodes, *nmemb * sizeof(*nodes));
1912 meshlink_node_t **p = result;
1914 for splay_each(node_t, n, mesh->nodes) {
1915 if(n->devclass == devclass) {
1916 *p++ = (meshlink_node_t *)n;
1922 meshlink_errno = MESHLINK_ENOMEM;
1925 pthread_mutex_unlock(&(mesh->mesh_mutex));
1930 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1931 if(!mesh || !node) {
1932 meshlink_errno = MESHLINK_EINVAL;
1936 dev_class_t devclass;
1938 pthread_mutex_lock(&(mesh->mesh_mutex));
1940 devclass = ((node_t *)node)->devclass;
1942 pthread_mutex_unlock(&(mesh->mesh_mutex));
1947 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1948 if(!mesh || !data || !len || !signature || !siglen) {
1949 meshlink_errno = MESHLINK_EINVAL;
1953 if(*siglen < MESHLINK_SIGLEN) {
1954 meshlink_errno = MESHLINK_EINVAL;
1958 pthread_mutex_lock(&(mesh->mesh_mutex));
1960 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1961 meshlink_errno = MESHLINK_EINTERNAL;
1962 pthread_mutex_unlock(&(mesh->mesh_mutex));
1966 *siglen = MESHLINK_SIGLEN;
1967 pthread_mutex_unlock(&(mesh->mesh_mutex));
1971 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1972 if(!mesh || !data || !len || !signature) {
1973 meshlink_errno = MESHLINK_EINVAL;
1977 if(siglen != MESHLINK_SIGLEN) {
1978 meshlink_errno = MESHLINK_EINVAL;
1982 pthread_mutex_lock(&(mesh->mesh_mutex));
1986 struct node_t *n = (struct node_t *)source;
1987 node_read_ecdsa_public_key(mesh, n);
1990 meshlink_errno = MESHLINK_EINTERNAL;
1993 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1996 pthread_mutex_unlock(&(mesh->mesh_mutex));
2000 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2001 char filename[PATH_MAX];
2003 pthread_mutex_lock(&(mesh->mesh_mutex));
2005 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2007 if(mkdir(filename, 0700) && errno != EEXIST) {
2008 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2009 meshlink_errno = MESHLINK_ESTORAGE;
2010 pthread_mutex_unlock(&(mesh->mesh_mutex));
2014 // Count the number of valid invitations, clean up old ones
2015 DIR *dir = opendir(filename);
2018 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2019 meshlink_errno = MESHLINK_ESTORAGE;
2020 pthread_mutex_unlock(&(mesh->mesh_mutex));
2027 time_t deadline = time(NULL) - 604800; // 1 week in the past
2029 while((ent = readdir(dir))) {
2030 if(strlen(ent->d_name) != 24) {
2034 char invname[PATH_MAX];
2037 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2038 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2042 if(!stat(invname, &st)) {
2043 if(mesh->invitation_key && deadline < st.st_mtime) {
2049 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2055 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2057 meshlink_errno = MESHLINK_ESTORAGE;
2058 pthread_mutex_unlock(&(mesh->mesh_mutex));
2064 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2066 // Remove the key if there are no outstanding invitations.
2070 if(mesh->invitation_key) {
2071 ecdsa_free(mesh->invitation_key);
2072 mesh->invitation_key = NULL;
2076 if(mesh->invitation_key) {
2077 pthread_mutex_unlock(&(mesh->mesh_mutex));
2081 // Create a new key if necessary.
2082 FILE *f = fopen(filename, "rb");
2085 if(errno != ENOENT) {
2086 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2087 meshlink_errno = MESHLINK_ESTORAGE;
2088 pthread_mutex_unlock(&(mesh->mesh_mutex));
2092 mesh->invitation_key = ecdsa_generate();
2094 if(!mesh->invitation_key) {
2095 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2096 meshlink_errno = MESHLINK_EINTERNAL;
2097 pthread_mutex_unlock(&(mesh->mesh_mutex));
2101 f = fopen(filename, "wb");
2104 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2105 meshlink_errno = MESHLINK_ESTORAGE;
2106 pthread_mutex_unlock(&(mesh->mesh_mutex));
2110 chmod(filename, 0600);
2111 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2114 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2117 if(!mesh->invitation_key) {
2118 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2119 meshlink_errno = MESHLINK_ESTORAGE;
2123 pthread_mutex_unlock(&(mesh->mesh_mutex));
2124 return mesh->invitation_key;
2127 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2128 if(!mesh || !node || !address) {
2129 meshlink_errno = MESHLINK_EINVAL;
2133 if(!is_valid_hostname(address)) {
2134 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2135 meshlink_errno = MESHLINK_EINVAL;
2139 if(port && !is_valid_port(port)) {
2140 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2141 meshlink_errno = MESHLINK_EINVAL;
2145 char *canonical_address;
2148 xasprintf(&canonical_address, "%s %s", address, port);
2150 canonical_address = xstrdup(address);
2153 pthread_mutex_lock(&(mesh->mesh_mutex));
2154 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2155 pthread_mutex_unlock(&(mesh->mesh_mutex));
2157 free(canonical_address);
2161 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2162 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2165 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2167 meshlink_errno = MESHLINK_EINVAL;
2171 char *address = meshlink_get_external_address(mesh);
2179 pthread_mutex_lock(&(mesh->mesh_mutex));
2180 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2181 pthread_mutex_unlock(&(mesh->mesh_mutex));
2187 int meshlink_get_port(meshlink_handle_t *mesh) {
2189 meshlink_errno = MESHLINK_EINVAL;
2194 meshlink_errno = MESHLINK_EINTERNAL;
2198 return atoi(mesh->myport);
2201 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2202 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2203 meshlink_errno = MESHLINK_EINVAL;
2207 if(mesh->myport && port == atoi(mesh->myport)) {
2211 if(!try_bind(port)) {
2212 meshlink_errno = MESHLINK_ENETWORK;
2218 pthread_mutex_lock(&(mesh->mesh_mutex));
2220 if(mesh->threadstarted) {
2221 meshlink_errno = MESHLINK_EINVAL;
2225 close_network_connections(mesh);
2226 exit_configuration(&mesh->config);
2229 snprintf(portstr, sizeof(portstr), "%d", port);
2230 portstr[sizeof(portstr) - 1] = 0;
2232 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2234 init_configuration(&mesh->config);
2236 if(!read_server_config(mesh)) {
2237 meshlink_errno = MESHLINK_ESTORAGE;
2238 } else if(!setup_network(mesh)) {
2239 meshlink_errno = MESHLINK_ENETWORK;
2245 pthread_mutex_unlock(&(mesh->mesh_mutex));
2250 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2251 mesh->invitation_timeout = timeout;
2254 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2255 meshlink_submesh_t *s = NULL;
2258 meshlink_errno = MESHLINK_EINVAL;
2263 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2266 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2267 meshlink_errno = MESHLINK_EINVAL;
2272 pthread_mutex_lock(&(mesh->mesh_mutex));
2274 // Check validity of the new node's name
2275 if(!check_id(name)) {
2276 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2277 meshlink_errno = MESHLINK_EINVAL;
2278 pthread_mutex_unlock(&(mesh->mesh_mutex));
2282 // Ensure no host configuration file with that name exists
2283 char filename[PATH_MAX];
2284 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2286 if(!access(filename, F_OK)) {
2287 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2288 meshlink_errno = MESHLINK_EEXIST;
2289 pthread_mutex_unlock(&(mesh->mesh_mutex));
2293 // Ensure no other nodes know about this name
2294 if(meshlink_get_node(mesh, name)) {
2295 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2296 meshlink_errno = MESHLINK_EEXIST;
2297 pthread_mutex_unlock(&(mesh->mesh_mutex));
2301 // Get the local address
2302 char *address = get_my_hostname(mesh, flags);
2305 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2306 meshlink_errno = MESHLINK_ERESOLV;
2307 pthread_mutex_unlock(&(mesh->mesh_mutex));
2311 if(!refresh_invitation_key(mesh)) {
2312 meshlink_errno = MESHLINK_EINTERNAL;
2313 pthread_mutex_unlock(&(mesh->mesh_mutex));
2319 // Create a hash of the key.
2320 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2321 sha512(fingerprint, strlen(fingerprint), hash);
2322 b64encode_urlsafe(hash, hash, 18);
2324 // Create a random cookie for this invitation.
2326 randomize(cookie, 18);
2328 // Create a filename that doesn't reveal the cookie itself
2329 char buf[18 + strlen(fingerprint)];
2330 char cookiehash[64];
2331 memcpy(buf, cookie, 18);
2332 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2333 sha512(buf, sizeof(buf), cookiehash);
2334 b64encode_urlsafe(cookiehash, cookiehash, 18);
2336 b64encode_urlsafe(cookie, cookie, 18);
2340 // Create a file containing the details of the invitation.
2341 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2342 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2345 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2346 meshlink_errno = MESHLINK_ESTORAGE;
2347 pthread_mutex_unlock(&(mesh->mesh_mutex));
2351 FILE *f = fdopen(ifd, "w");
2357 // Fill in the details.
2358 fprintf(f, "Name = %s\n", name);
2361 fprintf(f, "SubMesh = %s\n", s->name);
2364 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2366 // Copy Broadcast and Mode
2367 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2368 FILE *tc = fopen(filename, "r");
2373 while(fgets(buf, sizeof(buf), tc)) {
2374 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2375 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2378 // Make sure there is a newline character.
2379 if(!strchr(buf, '\n')) {
2387 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2388 meshlink_errno = MESHLINK_ESTORAGE;
2389 pthread_mutex_unlock(&(mesh->mesh_mutex));
2393 fprintf(f, "#---------------------------------------------------------------#\n");
2394 fprintf(f, "Name = %s\n", mesh->self->name);
2396 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2400 // Create an URL from the local address, key hash and cookie
2402 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2405 pthread_mutex_unlock(&(mesh->mesh_mutex));
2409 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2410 return meshlink_invite_ex(mesh, submesh, name, 0);
2413 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2414 if(!mesh || !invitation) {
2415 meshlink_errno = MESHLINK_EINVAL;
2419 pthread_mutex_lock(&(mesh->mesh_mutex));
2421 //Before doing meshlink_join make sure we are not connected to another mesh
2422 if(mesh->threadstarted) {
2423 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2424 meshlink_errno = MESHLINK_EINVAL;
2425 pthread_mutex_unlock(&(mesh->mesh_mutex));
2429 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2430 char copy[strlen(invitation) + 1];
2431 strcpy(copy, invitation);
2433 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2435 char *slash = strchr(copy, '/');
2443 if(strlen(slash) != 48) {
2447 char *address = copy;
2450 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2454 // Generate a throw-away key for the invitation.
2455 ecdsa_t *key = ecdsa_generate();
2458 meshlink_errno = MESHLINK_EINTERNAL;
2459 pthread_mutex_unlock(&(mesh->mesh_mutex));
2463 char *b64key = ecdsa_get_base64_public_key(key);
2467 while(address && *address) {
2468 // We allow commas in the address part to support multiple addresses in one invitation URL.
2469 comma = strchr(address, ',');
2475 // Split of the port
2476 port = strrchr(address, ':');
2484 // IPv6 address are enclosed in brackets, per RFC 3986
2485 if(*address == '[') {
2487 char *bracket = strchr(address, ']');
2500 // Connect to the meshlink daemon mentioned in the URL.
2501 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2504 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2505 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2507 if(mesh->sock == -1) {
2508 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2509 meshlink_errno = MESHLINK_ENETWORK;
2513 set_timeout(mesh->sock, 5000);
2515 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2516 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2517 meshlink_errno = MESHLINK_ENETWORK;
2518 closesocket(mesh->sock);
2526 meshlink_errno = MESHLINK_ERESOLV;
2529 if(mesh->sock != -1 || !comma) {
2536 if(mesh->sock == -1) {
2537 pthread_mutex_unlock(&mesh->mesh_mutex);
2541 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2543 // Tell him we have an invitation, and give him our throw-away key.
2547 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2548 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2549 closesocket(mesh->sock);
2550 meshlink_errno = MESHLINK_ENETWORK;
2551 pthread_mutex_unlock(&(mesh->mesh_mutex));
2557 char hisname[4096] = "";
2558 int code, hismajor, hisminor = 0;
2560 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) {
2561 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2562 closesocket(mesh->sock);
2563 meshlink_errno = MESHLINK_ENETWORK;
2564 pthread_mutex_unlock(&(mesh->mesh_mutex));
2568 // Check if the hash of the key he gave us matches the hash in the URL.
2569 char *fingerprint = mesh->line + 2;
2572 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2573 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2574 meshlink_errno = MESHLINK_EINTERNAL;
2575 pthread_mutex_unlock(&(mesh->mesh_mutex));
2579 if(memcmp(hishash, mesh->hash, 18)) {
2580 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2581 meshlink_errno = MESHLINK_EPEER;
2582 pthread_mutex_unlock(&(mesh->mesh_mutex));
2587 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2590 meshlink_errno = MESHLINK_EINTERNAL;
2591 pthread_mutex_unlock(&(mesh->mesh_mutex));
2595 // Start an SPTPS session
2596 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2597 meshlink_errno = MESHLINK_EINTERNAL;
2598 pthread_mutex_unlock(&(mesh->mesh_mutex));
2602 // Feed rest of input buffer to SPTPS
2603 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2604 meshlink_errno = MESHLINK_EPEER;
2605 pthread_mutex_unlock(&(mesh->mesh_mutex));
2611 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2613 if(errno == EINTR) {
2617 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2618 meshlink_errno = MESHLINK_ENETWORK;
2619 pthread_mutex_unlock(&(mesh->mesh_mutex));
2623 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2624 meshlink_errno = MESHLINK_EPEER;
2625 pthread_mutex_unlock(&(mesh->mesh_mutex));
2630 sptps_stop(&mesh->sptps);
2633 closesocket(mesh->sock);
2635 if(!mesh->success) {
2636 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2637 meshlink_errno = MESHLINK_EPEER;
2638 pthread_mutex_unlock(&(mesh->mesh_mutex));
2642 pthread_mutex_unlock(&(mesh->mesh_mutex));
2646 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2647 meshlink_errno = MESHLINK_EINVAL;
2648 pthread_mutex_unlock(&(mesh->mesh_mutex));
2652 char *meshlink_export(meshlink_handle_t *mesh) {
2654 meshlink_errno = MESHLINK_EINVAL;
2658 pthread_mutex_lock(&(mesh->mesh_mutex));
2660 char filename[PATH_MAX];
2661 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2662 FILE *f = fopen(filename, "r");
2665 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2666 meshlink_errno = MESHLINK_ESTORAGE;
2667 pthread_mutex_unlock(&(mesh->mesh_mutex));
2671 fseek(f, 0, SEEK_END);
2672 int fsize = ftell(f);
2675 size_t len = fsize + 9 + strlen(mesh->self->name);
2676 char *buf = xmalloc(len);
2677 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2679 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2680 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2683 meshlink_errno = MESHLINK_ESTORAGE;
2684 pthread_mutex_unlock(&(mesh->mesh_mutex));
2691 pthread_mutex_unlock(&(mesh->mesh_mutex));
2695 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2696 if(!mesh || !data) {
2697 meshlink_errno = MESHLINK_EINVAL;
2701 pthread_mutex_lock(&(mesh->mesh_mutex));
2703 if(strncmp(data, "Name = ", 7)) {
2704 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2705 meshlink_errno = MESHLINK_EPEER;
2706 pthread_mutex_unlock(&(mesh->mesh_mutex));
2710 char *end = strchr(data + 7, '\n');
2713 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2714 meshlink_errno = MESHLINK_EPEER;
2715 pthread_mutex_unlock(&(mesh->mesh_mutex));
2719 int len = end - (data + 7);
2721 memcpy(name, data + 7, len);
2724 if(!check_id(name)) {
2725 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2726 meshlink_errno = MESHLINK_EPEER;
2727 pthread_mutex_unlock(&(mesh->mesh_mutex));
2731 char filename[PATH_MAX];
2732 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2734 if(!access(filename, F_OK)) {
2735 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2736 meshlink_errno = MESHLINK_EEXIST;
2737 pthread_mutex_unlock(&(mesh->mesh_mutex));
2741 if(errno != ENOENT) {
2742 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2743 meshlink_errno = MESHLINK_ESTORAGE;
2744 pthread_mutex_unlock(&(mesh->mesh_mutex));
2748 FILE *f = fopen(filename, "w");
2751 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2752 meshlink_errno = MESHLINK_ESTORAGE;
2753 pthread_mutex_unlock(&(mesh->mesh_mutex));
2757 fwrite(end + 1, strlen(end + 1), 1, f);
2760 load_all_nodes(mesh);
2762 pthread_mutex_unlock(&(mesh->mesh_mutex));
2766 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2767 if(!mesh || !node) {
2768 meshlink_errno = MESHLINK_EINVAL;
2772 pthread_mutex_lock(&(mesh->mesh_mutex));
2776 n->status.blacklisted = true;
2777 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2779 //Make blacklisting persistent in the config file
2780 append_config_file(mesh, n->name, "blacklisted", "yes");
2782 //Immediately terminate any connections we have with the blacklisted node
2783 for list_each(connection_t, c, mesh->connections) {
2785 terminate_connection(mesh, c, c->status.active);
2789 pthread_mutex_unlock(&(mesh->mesh_mutex));
2792 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2793 if(!mesh || !node) {
2794 meshlink_errno = MESHLINK_EINVAL;
2798 pthread_mutex_lock(&(mesh->mesh_mutex));
2800 node_t *n = (node_t *)node;
2801 n->status.blacklisted = false;
2803 //TODO: remove blacklisted = yes from the config file
2805 pthread_mutex_unlock(&(mesh->mesh_mutex));
2809 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2810 mesh->default_blacklist = blacklist;
2813 /* Hint that a hostname may be found at an address
2814 * See header file for detailed comment.
2816 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2817 if(!mesh || !node || !addr) {
2821 // Ignore hints about ourself.
2822 if((node_t *)node == mesh->self) {
2826 pthread_mutex_lock(&(mesh->mesh_mutex));
2828 char *host = NULL, *port = NULL, *str = NULL;
2829 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2832 xasprintf(&str, "%s %s", host, port);
2834 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2835 modify_config_file(mesh, node->name, "Address", str, 5);
2837 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2845 pthread_mutex_unlock(&(mesh->mesh_mutex));
2846 // @TODO do we want to fire off a connection attempt right away?
2849 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2851 node_t *n = utcp->priv;
2852 meshlink_handle_t *mesh = n->mesh;
2853 return mesh->channel_accept_cb;
2856 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2857 meshlink_channel_t *channel = connection->priv;
2863 node_t *n = channel->node;
2864 meshlink_handle_t *mesh = n->mesh;
2866 if(n->status.destroyed) {
2867 meshlink_channel_close(mesh, channel);
2868 } else if(channel->receive_cb) {
2869 channel->receive_cb(mesh, channel, data, len);
2875 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2876 node_t *n = utcp_connection->utcp->priv;
2882 meshlink_handle_t *mesh = n->mesh;
2884 if(!mesh->channel_accept_cb) {
2888 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2890 channel->c = utcp_connection;
2892 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2893 utcp_accept(utcp_connection, channel_recv, channel);
2899 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2900 node_t *n = utcp->priv;
2902 if(n->status.destroyed) {
2906 meshlink_handle_t *mesh = n->mesh;
2907 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2910 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2911 if(!mesh || !channel) {
2912 meshlink_errno = MESHLINK_EINVAL;
2916 channel->receive_cb = cb;
2919 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2921 node_t *n = (node_t *)source;
2927 utcp_recv(n->utcp, data, len);
2930 static void channel_poll(struct utcp_connection *connection, size_t len) {
2931 meshlink_channel_t *channel = connection->priv;
2937 node_t *n = channel->node;
2938 meshlink_handle_t *mesh = n->mesh;
2940 if(channel->poll_cb) {
2941 channel->poll_cb(mesh, channel, len);
2945 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2947 channel->poll_cb = cb;
2948 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2951 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2953 meshlink_errno = MESHLINK_EINVAL;
2957 pthread_mutex_lock(&mesh->mesh_mutex);
2958 mesh->channel_accept_cb = cb;
2959 mesh->receive_cb = channel_receive;
2961 for splay_each(node_t, n, mesh->nodes) {
2962 if(!n->utcp && n != mesh->self) {
2963 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2967 pthread_mutex_unlock(&mesh->mesh_mutex);
2970 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) {
2972 abort(); // TODO: handle non-NULL data
2975 if(!mesh || !node) {
2976 meshlink_errno = MESHLINK_EINVAL;
2980 node_t *n = (node_t *)node;
2983 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2984 mesh->receive_cb = channel_receive;
2987 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2992 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2994 channel->receive_cb = cb;
2995 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2998 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3006 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) {
3007 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3010 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3011 if(!mesh || !channel) {
3012 meshlink_errno = MESHLINK_EINVAL;
3016 utcp_shutdown(channel->c, direction);
3019 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3020 if(!mesh || !channel) {
3021 meshlink_errno = MESHLINK_EINVAL;
3025 utcp_close(channel->c);
3029 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3030 if(!mesh || !channel) {
3031 meshlink_errno = MESHLINK_EINVAL;
3040 meshlink_errno = MESHLINK_EINVAL;
3044 // TODO: more finegrained locking.
3045 // Ideally we want to put the data into the UTCP connection's send buffer.
3046 // Then, preferrably only if there is room in the receiver window,
3047 // kick the meshlink thread to go send packets.
3049 pthread_mutex_lock(&mesh->mesh_mutex);
3050 ssize_t retval = utcp_send(channel->c, data, len);
3051 pthread_mutex_unlock(&mesh->mesh_mutex);
3054 meshlink_errno = MESHLINK_ENETWORK;
3060 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3061 if(!mesh || !channel) {
3062 meshlink_errno = MESHLINK_EINVAL;
3066 return channel->c->flags;
3069 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3070 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3071 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3074 if(mesh->node_status_cb) {
3075 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
3079 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3080 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3084 n->status.duplicate = true;
3085 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3088 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3092 meshlink_errno = MESHLINK_EINVAL;
3096 pthread_mutex_lock(&mesh->mesh_mutex);
3098 if(mesh->discovery == enable) {
3102 if(mesh->threadstarted) {
3104 discovery_start(mesh);
3106 discovery_stop(mesh);
3110 mesh->discovery = enable;
3113 pthread_mutex_unlock(&mesh->mesh_mutex);
3117 meshlink_errno = MESHLINK_ENOTSUP;
3121 static void __attribute__((constructor)) meshlink_init(void) {
3124 randomize(&seed, sizeof(seed));
3128 static void __attribute__((destructor)) meshlink_exit(void) {
3132 /// Device class traits
3133 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3134 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3135 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3136 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3137 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN