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 node_t *n = (node_t *)destination;
1737 if(n->status.blacklisted) {
1738 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1742 // Prepare the packet
1743 vpn_packet_t *packet = malloc(sizeof(*packet));
1746 meshlink_errno = MESHLINK_ENOMEM;
1750 packet->probe = false;
1751 packet->tcp = false;
1752 packet->len = len + sizeof(*hdr);
1754 hdr = (meshlink_packethdr_t *)packet->data;
1755 memset(hdr, 0, sizeof(*hdr));
1756 // leave the last byte as 0 to make sure strings are always
1757 // null-terminated if they are longer than the buffer
1758 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1759 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1761 memcpy(packet->data + sizeof(*hdr), data, len);
1764 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1766 meshlink_errno = MESHLINK_ENOMEM;
1770 // Notify event loop
1771 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1776 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1778 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1784 mesh->self->in_packets++;
1785 mesh->self->in_bytes += packet->len;
1786 route(mesh, mesh->self, packet);
1789 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1790 if(!mesh || !destination) {
1791 meshlink_errno = MESHLINK_EINVAL;
1795 pthread_mutex_lock(&(mesh->mesh_mutex));
1797 node_t *n = (node_t *)destination;
1799 if(!n->status.reachable) {
1800 pthread_mutex_unlock(&(mesh->mesh_mutex));
1803 } else if(n->mtuprobes > 30 && n->minmtu) {
1804 pthread_mutex_unlock(&(mesh->mesh_mutex));
1807 pthread_mutex_unlock(&(mesh->mesh_mutex));
1812 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1813 if(!mesh || !node) {
1814 meshlink_errno = MESHLINK_EINVAL;
1818 pthread_mutex_lock(&(mesh->mesh_mutex));
1820 node_t *n = (node_t *)node;
1822 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1823 meshlink_errno = MESHLINK_EINTERNAL;
1824 pthread_mutex_unlock(&(mesh->mesh_mutex));
1828 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1831 meshlink_errno = MESHLINK_EINTERNAL;
1834 pthread_mutex_unlock(&(mesh->mesh_mutex));
1838 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1840 meshlink_errno = MESHLINK_EINVAL;
1844 return (meshlink_node_t *)mesh->self;
1847 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1848 if(!mesh || !name) {
1849 meshlink_errno = MESHLINK_EINVAL;
1853 meshlink_node_t *node = NULL;
1855 pthread_mutex_lock(&(mesh->mesh_mutex));
1856 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1857 pthread_mutex_unlock(&(mesh->mesh_mutex));
1861 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1862 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1863 meshlink_errno = MESHLINK_EINVAL;
1867 meshlink_node_t **result;
1870 pthread_mutex_lock(&(mesh->mesh_mutex));
1872 *nmemb = mesh->nodes->count;
1873 result = realloc(nodes, *nmemb * sizeof(*nodes));
1876 meshlink_node_t **p = result;
1878 for splay_each(node_t, n, mesh->nodes) {
1879 *p++ = (meshlink_node_t *)n;
1884 meshlink_errno = MESHLINK_ENOMEM;
1887 pthread_mutex_unlock(&(mesh->mesh_mutex));
1892 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) {
1893 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1894 meshlink_errno = MESHLINK_EINVAL;
1898 meshlink_node_t **result;
1900 pthread_mutex_lock(&(mesh->mesh_mutex));
1904 for splay_each(node_t, n, mesh->nodes) {
1905 if(n->devclass == devclass) {
1906 *nmemb = *nmemb + 1;
1912 pthread_mutex_unlock(&(mesh->mesh_mutex));
1916 result = realloc(nodes, *nmemb * sizeof(*nodes));
1919 meshlink_node_t **p = result;
1921 for splay_each(node_t, n, mesh->nodes) {
1922 if(n->devclass == devclass) {
1923 *p++ = (meshlink_node_t *)n;
1929 meshlink_errno = MESHLINK_ENOMEM;
1932 pthread_mutex_unlock(&(mesh->mesh_mutex));
1937 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1938 if(!mesh || !node) {
1939 meshlink_errno = MESHLINK_EINVAL;
1943 dev_class_t devclass;
1945 pthread_mutex_lock(&(mesh->mesh_mutex));
1947 devclass = ((node_t *)node)->devclass;
1949 pthread_mutex_unlock(&(mesh->mesh_mutex));
1954 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1955 if(!mesh || !data || !len || !signature || !siglen) {
1956 meshlink_errno = MESHLINK_EINVAL;
1960 if(*siglen < MESHLINK_SIGLEN) {
1961 meshlink_errno = MESHLINK_EINVAL;
1965 pthread_mutex_lock(&(mesh->mesh_mutex));
1967 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1968 meshlink_errno = MESHLINK_EINTERNAL;
1969 pthread_mutex_unlock(&(mesh->mesh_mutex));
1973 *siglen = MESHLINK_SIGLEN;
1974 pthread_mutex_unlock(&(mesh->mesh_mutex));
1978 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1979 if(!mesh || !data || !len || !signature) {
1980 meshlink_errno = MESHLINK_EINVAL;
1984 if(siglen != MESHLINK_SIGLEN) {
1985 meshlink_errno = MESHLINK_EINVAL;
1989 pthread_mutex_lock(&(mesh->mesh_mutex));
1993 struct node_t *n = (struct node_t *)source;
1994 node_read_ecdsa_public_key(mesh, n);
1997 meshlink_errno = MESHLINK_EINTERNAL;
2000 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2003 pthread_mutex_unlock(&(mesh->mesh_mutex));
2007 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2008 char filename[PATH_MAX];
2010 pthread_mutex_lock(&(mesh->mesh_mutex));
2012 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2014 if(mkdir(filename, 0700) && errno != EEXIST) {
2015 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2016 meshlink_errno = MESHLINK_ESTORAGE;
2017 pthread_mutex_unlock(&(mesh->mesh_mutex));
2021 // Count the number of valid invitations, clean up old ones
2022 DIR *dir = opendir(filename);
2025 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2026 meshlink_errno = MESHLINK_ESTORAGE;
2027 pthread_mutex_unlock(&(mesh->mesh_mutex));
2034 time_t deadline = time(NULL) - 604800; // 1 week in the past
2036 while((ent = readdir(dir))) {
2037 if(strlen(ent->d_name) != 24) {
2041 char invname[PATH_MAX];
2044 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2045 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2049 if(!stat(invname, &st)) {
2050 if(mesh->invitation_key && deadline < st.st_mtime) {
2056 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2062 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2064 meshlink_errno = MESHLINK_ESTORAGE;
2065 pthread_mutex_unlock(&(mesh->mesh_mutex));
2071 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2073 // Remove the key if there are no outstanding invitations.
2077 if(mesh->invitation_key) {
2078 ecdsa_free(mesh->invitation_key);
2079 mesh->invitation_key = NULL;
2083 if(mesh->invitation_key) {
2084 pthread_mutex_unlock(&(mesh->mesh_mutex));
2088 // Create a new key if necessary.
2089 FILE *f = fopen(filename, "rb");
2092 if(errno != ENOENT) {
2093 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2094 meshlink_errno = MESHLINK_ESTORAGE;
2095 pthread_mutex_unlock(&(mesh->mesh_mutex));
2099 mesh->invitation_key = ecdsa_generate();
2101 if(!mesh->invitation_key) {
2102 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2103 meshlink_errno = MESHLINK_EINTERNAL;
2104 pthread_mutex_unlock(&(mesh->mesh_mutex));
2108 f = fopen(filename, "wb");
2111 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2112 meshlink_errno = MESHLINK_ESTORAGE;
2113 pthread_mutex_unlock(&(mesh->mesh_mutex));
2117 chmod(filename, 0600);
2118 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2121 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2124 if(!mesh->invitation_key) {
2125 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2126 meshlink_errno = MESHLINK_ESTORAGE;
2130 pthread_mutex_unlock(&(mesh->mesh_mutex));
2131 return mesh->invitation_key;
2134 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2135 if(!mesh || !node || !address) {
2136 meshlink_errno = MESHLINK_EINVAL;
2140 if(!is_valid_hostname(address)) {
2141 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2142 meshlink_errno = MESHLINK_EINVAL;
2146 if(port && !is_valid_port(port)) {
2147 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2148 meshlink_errno = MESHLINK_EINVAL;
2152 char *canonical_address;
2155 xasprintf(&canonical_address, "%s %s", address, port);
2157 canonical_address = xstrdup(address);
2160 pthread_mutex_lock(&(mesh->mesh_mutex));
2161 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2162 pthread_mutex_unlock(&(mesh->mesh_mutex));
2164 free(canonical_address);
2168 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2169 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2172 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2174 meshlink_errno = MESHLINK_EINVAL;
2178 char *address = meshlink_get_external_address(mesh);
2186 pthread_mutex_lock(&(mesh->mesh_mutex));
2187 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2188 pthread_mutex_unlock(&(mesh->mesh_mutex));
2194 int meshlink_get_port(meshlink_handle_t *mesh) {
2196 meshlink_errno = MESHLINK_EINVAL;
2201 meshlink_errno = MESHLINK_EINTERNAL;
2205 return atoi(mesh->myport);
2208 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2209 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2210 meshlink_errno = MESHLINK_EINVAL;
2214 if(mesh->myport && port == atoi(mesh->myport)) {
2218 if(!try_bind(port)) {
2219 meshlink_errno = MESHLINK_ENETWORK;
2225 pthread_mutex_lock(&(mesh->mesh_mutex));
2227 if(mesh->threadstarted) {
2228 meshlink_errno = MESHLINK_EINVAL;
2232 close_network_connections(mesh);
2233 exit_configuration(&mesh->config);
2236 snprintf(portstr, sizeof(portstr), "%d", port);
2237 portstr[sizeof(portstr) - 1] = 0;
2239 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2241 init_configuration(&mesh->config);
2243 if(!read_server_config(mesh)) {
2244 meshlink_errno = MESHLINK_ESTORAGE;
2245 } else if(!setup_network(mesh)) {
2246 meshlink_errno = MESHLINK_ENETWORK;
2252 pthread_mutex_unlock(&(mesh->mesh_mutex));
2257 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2258 mesh->invitation_timeout = timeout;
2261 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2262 meshlink_submesh_t *s = NULL;
2265 meshlink_errno = MESHLINK_EINVAL;
2270 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2273 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2274 meshlink_errno = MESHLINK_EINVAL;
2279 pthread_mutex_lock(&(mesh->mesh_mutex));
2281 // Check validity of the new node's name
2282 if(!check_id(name)) {
2283 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2284 meshlink_errno = MESHLINK_EINVAL;
2285 pthread_mutex_unlock(&(mesh->mesh_mutex));
2289 // Ensure no host configuration file with that name exists
2290 char filename[PATH_MAX];
2291 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2293 if(!access(filename, F_OK)) {
2294 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2295 meshlink_errno = MESHLINK_EEXIST;
2296 pthread_mutex_unlock(&(mesh->mesh_mutex));
2300 // Ensure no other nodes know about this name
2301 if(meshlink_get_node(mesh, name)) {
2302 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2303 meshlink_errno = MESHLINK_EEXIST;
2304 pthread_mutex_unlock(&(mesh->mesh_mutex));
2308 // Get the local address
2309 char *address = get_my_hostname(mesh, flags);
2312 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2313 meshlink_errno = MESHLINK_ERESOLV;
2314 pthread_mutex_unlock(&(mesh->mesh_mutex));
2318 if(!refresh_invitation_key(mesh)) {
2319 meshlink_errno = MESHLINK_EINTERNAL;
2320 pthread_mutex_unlock(&(mesh->mesh_mutex));
2326 // Create a hash of the key.
2327 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2328 sha512(fingerprint, strlen(fingerprint), hash);
2329 b64encode_urlsafe(hash, hash, 18);
2331 // Create a random cookie for this invitation.
2333 randomize(cookie, 18);
2335 // Create a filename that doesn't reveal the cookie itself
2336 char buf[18 + strlen(fingerprint)];
2337 char cookiehash[64];
2338 memcpy(buf, cookie, 18);
2339 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2340 sha512(buf, sizeof(buf), cookiehash);
2341 b64encode_urlsafe(cookiehash, cookiehash, 18);
2343 b64encode_urlsafe(cookie, cookie, 18);
2347 // Create a file containing the details of the invitation.
2348 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2349 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2352 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2353 meshlink_errno = MESHLINK_ESTORAGE;
2354 pthread_mutex_unlock(&(mesh->mesh_mutex));
2358 FILE *f = fdopen(ifd, "w");
2364 // Fill in the details.
2365 fprintf(f, "Name = %s\n", name);
2368 fprintf(f, "SubMesh = %s\n", s->name);
2371 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2373 // Copy Broadcast and Mode
2374 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2375 FILE *tc = fopen(filename, "r");
2380 while(fgets(buf, sizeof(buf), tc)) {
2381 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2382 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2385 // Make sure there is a newline character.
2386 if(!strchr(buf, '\n')) {
2394 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2395 meshlink_errno = MESHLINK_ESTORAGE;
2396 pthread_mutex_unlock(&(mesh->mesh_mutex));
2400 fprintf(f, "#---------------------------------------------------------------#\n");
2401 fprintf(f, "Name = %s\n", mesh->self->name);
2403 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2407 // Create an URL from the local address, key hash and cookie
2409 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2412 pthread_mutex_unlock(&(mesh->mesh_mutex));
2416 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2417 return meshlink_invite_ex(mesh, submesh, name, 0);
2420 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2421 if(!mesh || !invitation) {
2422 meshlink_errno = MESHLINK_EINVAL;
2426 pthread_mutex_lock(&(mesh->mesh_mutex));
2428 //Before doing meshlink_join make sure we are not connected to another mesh
2429 if(mesh->threadstarted) {
2430 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2431 meshlink_errno = MESHLINK_EINVAL;
2432 pthread_mutex_unlock(&(mesh->mesh_mutex));
2436 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2437 char copy[strlen(invitation) + 1];
2438 strcpy(copy, invitation);
2440 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2442 char *slash = strchr(copy, '/');
2450 if(strlen(slash) != 48) {
2454 char *address = copy;
2457 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2461 // Generate a throw-away key for the invitation.
2462 ecdsa_t *key = ecdsa_generate();
2465 meshlink_errno = MESHLINK_EINTERNAL;
2466 pthread_mutex_unlock(&(mesh->mesh_mutex));
2470 char *b64key = ecdsa_get_base64_public_key(key);
2474 while(address && *address) {
2475 // We allow commas in the address part to support multiple addresses in one invitation URL.
2476 comma = strchr(address, ',');
2482 // Split of the port
2483 port = strrchr(address, ':');
2491 // IPv6 address are enclosed in brackets, per RFC 3986
2492 if(*address == '[') {
2494 char *bracket = strchr(address, ']');
2507 // Connect to the meshlink daemon mentioned in the URL.
2508 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2511 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2512 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2514 if(mesh->sock == -1) {
2515 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2516 meshlink_errno = MESHLINK_ENETWORK;
2520 set_timeout(mesh->sock, 5000);
2522 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2523 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2524 meshlink_errno = MESHLINK_ENETWORK;
2525 closesocket(mesh->sock);
2533 meshlink_errno = MESHLINK_ERESOLV;
2536 if(mesh->sock != -1 || !comma) {
2543 if(mesh->sock == -1) {
2544 pthread_mutex_unlock(&mesh->mesh_mutex);
2548 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2550 // Tell him we have an invitation, and give him our throw-away key.
2554 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2555 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2556 closesocket(mesh->sock);
2557 meshlink_errno = MESHLINK_ENETWORK;
2558 pthread_mutex_unlock(&(mesh->mesh_mutex));
2564 char hisname[4096] = "";
2565 int code, hismajor, hisminor = 0;
2567 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) {
2568 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2569 closesocket(mesh->sock);
2570 meshlink_errno = MESHLINK_ENETWORK;
2571 pthread_mutex_unlock(&(mesh->mesh_mutex));
2575 // Check if the hash of the key he gave us matches the hash in the URL.
2576 char *fingerprint = mesh->line + 2;
2579 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2580 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2581 meshlink_errno = MESHLINK_EINTERNAL;
2582 pthread_mutex_unlock(&(mesh->mesh_mutex));
2586 if(memcmp(hishash, mesh->hash, 18)) {
2587 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2588 meshlink_errno = MESHLINK_EPEER;
2589 pthread_mutex_unlock(&(mesh->mesh_mutex));
2594 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2597 meshlink_errno = MESHLINK_EINTERNAL;
2598 pthread_mutex_unlock(&(mesh->mesh_mutex));
2602 // Start an SPTPS session
2603 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2604 meshlink_errno = MESHLINK_EINTERNAL;
2605 pthread_mutex_unlock(&(mesh->mesh_mutex));
2609 // Feed rest of input buffer to SPTPS
2610 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2611 meshlink_errno = MESHLINK_EPEER;
2612 pthread_mutex_unlock(&(mesh->mesh_mutex));
2618 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2620 if(errno == EINTR) {
2624 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2625 meshlink_errno = MESHLINK_ENETWORK;
2626 pthread_mutex_unlock(&(mesh->mesh_mutex));
2630 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2631 meshlink_errno = MESHLINK_EPEER;
2632 pthread_mutex_unlock(&(mesh->mesh_mutex));
2637 sptps_stop(&mesh->sptps);
2640 closesocket(mesh->sock);
2642 if(!mesh->success) {
2643 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2644 meshlink_errno = MESHLINK_EPEER;
2645 pthread_mutex_unlock(&(mesh->mesh_mutex));
2649 pthread_mutex_unlock(&(mesh->mesh_mutex));
2653 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2654 meshlink_errno = MESHLINK_EINVAL;
2655 pthread_mutex_unlock(&(mesh->mesh_mutex));
2659 char *meshlink_export(meshlink_handle_t *mesh) {
2661 meshlink_errno = MESHLINK_EINVAL;
2665 pthread_mutex_lock(&(mesh->mesh_mutex));
2667 char filename[PATH_MAX];
2668 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2669 FILE *f = fopen(filename, "r");
2672 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2673 meshlink_errno = MESHLINK_ESTORAGE;
2674 pthread_mutex_unlock(&(mesh->mesh_mutex));
2678 fseek(f, 0, SEEK_END);
2679 int fsize = ftell(f);
2682 size_t len = fsize + 9 + strlen(mesh->self->name);
2683 char *buf = xmalloc(len);
2684 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2686 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2687 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2690 meshlink_errno = MESHLINK_ESTORAGE;
2691 pthread_mutex_unlock(&(mesh->mesh_mutex));
2698 pthread_mutex_unlock(&(mesh->mesh_mutex));
2702 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2703 if(!mesh || !data) {
2704 meshlink_errno = MESHLINK_EINVAL;
2708 pthread_mutex_lock(&(mesh->mesh_mutex));
2710 if(strncmp(data, "Name = ", 7)) {
2711 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2712 meshlink_errno = MESHLINK_EPEER;
2713 pthread_mutex_unlock(&(mesh->mesh_mutex));
2717 char *end = strchr(data + 7, '\n');
2720 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2721 meshlink_errno = MESHLINK_EPEER;
2722 pthread_mutex_unlock(&(mesh->mesh_mutex));
2726 int len = end - (data + 7);
2728 memcpy(name, data + 7, len);
2731 if(!check_id(name)) {
2732 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2733 meshlink_errno = MESHLINK_EPEER;
2734 pthread_mutex_unlock(&(mesh->mesh_mutex));
2738 char filename[PATH_MAX];
2739 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2741 if(!access(filename, F_OK)) {
2742 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2743 meshlink_errno = MESHLINK_EEXIST;
2744 pthread_mutex_unlock(&(mesh->mesh_mutex));
2748 if(errno != ENOENT) {
2749 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2750 meshlink_errno = MESHLINK_ESTORAGE;
2751 pthread_mutex_unlock(&(mesh->mesh_mutex));
2755 FILE *f = fopen(filename, "w");
2758 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2759 meshlink_errno = MESHLINK_ESTORAGE;
2760 pthread_mutex_unlock(&(mesh->mesh_mutex));
2764 fwrite(end + 1, strlen(end + 1), 1, f);
2767 load_all_nodes(mesh);
2769 pthread_mutex_unlock(&(mesh->mesh_mutex));
2773 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2774 if(!mesh || !node) {
2775 meshlink_errno = MESHLINK_EINVAL;
2779 pthread_mutex_lock(&(mesh->mesh_mutex));
2784 if(n == mesh->self) {
2785 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2786 meshlink_errno = MESHLINK_EINVAL;
2787 pthread_mutex_unlock(&(mesh->mesh_mutex));
2791 if(n->status.blacklisted) {
2792 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2793 pthread_mutex_unlock(&(mesh->mesh_mutex));
2797 n->status.blacklisted = true;
2798 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2800 //Make blacklisting persistent in the config file
2801 append_config_file(mesh, n->name, "blacklisted", "yes");
2803 //Immediately terminate any connections we have with the blacklisted node
2804 for list_each(connection_t, c, mesh->connections) {
2806 terminate_connection(mesh, c, c->status.active);
2810 utcp_abort_all_connections(n->utcp);
2816 n->status.udp_confirmed = false;
2818 if(n->status.reachable) {
2819 update_node_status(mesh, n);
2822 pthread_mutex_unlock(&(mesh->mesh_mutex));
2825 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2826 if(!mesh || !node) {
2827 meshlink_errno = MESHLINK_EINVAL;
2831 pthread_mutex_lock(&(mesh->mesh_mutex));
2833 node_t *n = (node_t *)node;
2835 if(!n->status.blacklisted) {
2836 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2837 meshlink_errno = MESHLINK_EINVAL;
2838 pthread_mutex_unlock(&(mesh->mesh_mutex));
2842 n->status.blacklisted = false;
2844 if(n->status.reachable) {
2845 update_node_status(mesh, n);
2848 //Remove blacklisting from the config file
2849 append_config_file(mesh, n->name, "blacklisted", NULL);
2851 pthread_mutex_unlock(&(mesh->mesh_mutex));
2855 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2856 mesh->default_blacklist = blacklist;
2859 /* Hint that a hostname may be found at an address
2860 * See header file for detailed comment.
2862 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2863 if(!mesh || !node || !addr) {
2867 // Ignore hints about ourself.
2868 if((node_t *)node == mesh->self) {
2872 pthread_mutex_lock(&(mesh->mesh_mutex));
2874 char *host = NULL, *port = NULL, *str = NULL;
2875 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2878 xasprintf(&str, "%s %s", host, port);
2880 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2881 modify_config_file(mesh, node->name, "Address", str, 5);
2883 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2891 pthread_mutex_unlock(&(mesh->mesh_mutex));
2892 // @TODO do we want to fire off a connection attempt right away?
2895 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2897 node_t *n = utcp->priv;
2898 meshlink_handle_t *mesh = n->mesh;
2899 return mesh->channel_accept_cb;
2902 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2903 meshlink_channel_t *channel = connection->priv;
2909 node_t *n = channel->node;
2910 meshlink_handle_t *mesh = n->mesh;
2912 if(n->status.destroyed) {
2913 meshlink_channel_close(mesh, channel);
2914 } else if(channel->receive_cb) {
2915 channel->receive_cb(mesh, channel, data, len);
2921 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2922 node_t *n = utcp_connection->utcp->priv;
2928 meshlink_handle_t *mesh = n->mesh;
2930 if(!mesh->channel_accept_cb) {
2934 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2936 channel->c = utcp_connection;
2938 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2939 utcp_accept(utcp_connection, channel_recv, channel);
2945 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2946 node_t *n = utcp->priv;
2948 if(n->status.destroyed) {
2952 meshlink_handle_t *mesh = n->mesh;
2953 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2956 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2957 if(!mesh || !channel) {
2958 meshlink_errno = MESHLINK_EINVAL;
2962 channel->receive_cb = cb;
2965 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2967 node_t *n = (node_t *)source;
2973 utcp_recv(n->utcp, data, len);
2976 static void channel_poll(struct utcp_connection *connection, size_t len) {
2977 meshlink_channel_t *channel = connection->priv;
2983 node_t *n = channel->node;
2984 meshlink_handle_t *mesh = n->mesh;
2986 if(channel->poll_cb) {
2987 channel->poll_cb(mesh, channel, len);
2991 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2993 channel->poll_cb = cb;
2994 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2997 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2999 meshlink_errno = MESHLINK_EINVAL;
3003 pthread_mutex_lock(&mesh->mesh_mutex);
3004 mesh->channel_accept_cb = cb;
3005 mesh->receive_cb = channel_receive;
3007 for splay_each(node_t, n, mesh->nodes) {
3008 if(!n->utcp && n != mesh->self) {
3009 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3013 pthread_mutex_unlock(&mesh->mesh_mutex);
3016 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) {
3018 abort(); // TODO: handle non-NULL data
3021 if(!mesh || !node) {
3022 meshlink_errno = MESHLINK_EINVAL;
3026 node_t *n = (node_t *)node;
3029 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3030 mesh->receive_cb = channel_receive;
3033 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3038 if(n->status.blacklisted) {
3039 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3043 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3045 channel->receive_cb = cb;
3046 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3049 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3057 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) {
3058 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3061 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3062 if(!mesh || !channel) {
3063 meshlink_errno = MESHLINK_EINVAL;
3067 utcp_shutdown(channel->c, direction);
3070 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3071 if(!mesh || !channel) {
3072 meshlink_errno = MESHLINK_EINVAL;
3076 utcp_close(channel->c);
3080 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3081 if(!mesh || !channel) {
3082 meshlink_errno = MESHLINK_EINVAL;
3091 meshlink_errno = MESHLINK_EINVAL;
3095 // TODO: more finegrained locking.
3096 // Ideally we want to put the data into the UTCP connection's send buffer.
3097 // Then, preferrably only if there is room in the receiver window,
3098 // kick the meshlink thread to go send packets.
3100 pthread_mutex_lock(&mesh->mesh_mutex);
3101 ssize_t retval = utcp_send(channel->c, data, len);
3102 pthread_mutex_unlock(&mesh->mesh_mutex);
3105 meshlink_errno = MESHLINK_ENETWORK;
3111 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3112 if(!mesh || !channel) {
3113 meshlink_errno = MESHLINK_EINVAL;
3117 return channel->c->flags;
3120 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3121 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3122 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3125 if(mesh->node_status_cb) {
3126 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3130 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3131 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3135 n->status.duplicate = true;
3136 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3139 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3143 meshlink_errno = MESHLINK_EINVAL;
3147 pthread_mutex_lock(&mesh->mesh_mutex);
3149 if(mesh->discovery == enable) {
3153 if(mesh->threadstarted) {
3155 discovery_start(mesh);
3157 discovery_stop(mesh);
3161 mesh->discovery = enable;
3164 pthread_mutex_unlock(&mesh->mesh_mutex);
3168 meshlink_errno = MESHLINK_ENOTSUP;
3172 static void __attribute__((constructor)) meshlink_init(void) {
3175 randomize(&seed, sizeof(seed));
3179 static void __attribute__((destructor)) meshlink_exit(void) {
3183 /// Device class traits
3184 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3185 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3186 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3187 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3188 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN