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
52 __thread meshlink_errno_t meshlink_errno;
53 meshlink_log_cb_t global_log_cb;
54 meshlink_log_level_t global_log_level;
56 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
58 //TODO: this can go away completely
59 const var_t variables[] = {
60 /* Server configuration */
61 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
63 /* Host configuration */
64 {"SubMesh", VAR_HOST | VAR_SAFE},
65 {"CanonicalAddress", VAR_HOST},
66 {"Address", VAR_HOST | VAR_MULTIPLE},
67 {"ECDSAPublicKey", VAR_HOST},
72 static bool fcopy(FILE *out, const char *filename) {
73 FILE *in = fopen(filename, "r");
76 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
83 while((len = fread(buf, 1, sizeof(buf), in))) {
84 fwrite(buf, len, 1, out);
91 static int rstrip(char *value) {
92 int len = strlen(value);
94 while(len && strchr("\t\r\n ", value[len - 1])) {
101 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
104 if(!filename || (*hostname && *port)) {
108 FILE *f = fopen(filename, "r");
114 while(fgets(line, sizeof(line), f)) {
120 p += strcspn(p, "\t =");
126 q = p + strspn(p, "\t ");
129 q += 1 + strspn(q + 1, "\t ");
132 // q is now pointing to the hostname
134 p = q + strcspn(q, "\t ");
140 p += strspn(p, "\t ");
141 p[strcspn(p, "\t ")] = 0;
142 // p is now pointing to the port, if present
144 if(!*port && !strcasecmp(line, "Port")) {
146 } else if(!strcasecmp(line, "CanonicalAddress")) {
147 *hostname = xstrdup(q);
155 if(*hostname && *port) {
163 static bool is_valid_hostname(const char *hostname) {
168 for(const char *p = hostname; *p; p++) {
169 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
177 static bool is_valid_port(const char *port) {
184 unsigned long int result = strtoul(port, &end, 10);
185 return result && result < 65536 && !*end;
188 for(const char *p = port; *p; p++) {
189 if(!(isalnum(*p) || *p == '-')) {
197 static void set_timeout(int sock, int timeout) {
202 tv.tv_sec = timeout / 1000;
203 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
205 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
206 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
209 struct socket_in_netns_params {
218 static void *socket_in_netns_thread(void *arg) {
219 struct socket_in_netns_params *params = arg;
221 if(setns(params->netns, CLONE_NEWNET) == -1) {
222 meshlink_errno = MESHLINK_EINVAL;
226 params->fd = socket(params->domain, params->type, params->protocol);
232 static int socket_in_netns(int domain, int type, int protocol, int netns) {
234 return socket(domain, type, protocol);
238 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
242 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
243 pthread_join(thr, NULL);
253 // Find out what local address a socket would use if we connect to the given address.
254 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
255 // of both endpoints, but this will actually not send any UDP packet.
256 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
257 struct addrinfo *rai = NULL;
258 const struct addrinfo hint = {
259 .ai_family = AF_UNSPEC,
260 .ai_socktype = SOCK_DGRAM,
261 .ai_protocol = IPPROTO_UDP,
264 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
268 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
275 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
283 struct sockaddr_storage sn;
284 socklen_t sl = sizeof(sn);
286 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
293 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
300 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
301 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
304 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
305 char *hostname = NULL;
307 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
308 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
309 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
312 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
313 if(family != AF_UNSPEC && aip->ai_family != family) {
317 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
320 set_timeout(s, 5000);
322 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
329 send(s, request, sizeof(request) - 1, 0);
330 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
335 if(line[len - 1] == '\n') {
339 char *p = strrchr(line, '\n');
342 hostname = xstrdup(p + 1);
358 // Check that the hostname is reasonable
359 if(hostname && !is_valid_hostname(hostname)) {
365 meshlink_errno = MESHLINK_ERESOLV;
371 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
374 // Determine address of the local interface used for outgoing connections.
375 char localaddr[NI_MAXHOST];
376 bool success = false;
378 if(family == AF_INET) {
379 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
380 } else if(family == AF_INET6) {
381 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
385 meshlink_errno = MESHLINK_ENETWORK;
389 return xstrdup(localaddr);
392 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
393 for(int i = 0; i < n; i++) {
398 // Ignore duplicate hostnames
401 for(int j = 0; j < i; j++) {
406 if(strcmp(host[i], host[j])) {
410 if(strcmp(port[i], port[j])) {
428 // This gets the hostname part for use in invitation URLs
429 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
430 char *hostname[4] = {NULL};
431 char *port[4] = {NULL};
432 char *hostport = NULL;
434 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
435 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
438 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
439 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
442 // Add local addresses if requested
443 if(flags & MESHLINK_INVITE_LOCAL) {
444 if(flags & MESHLINK_INVITE_IPV4) {
445 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
448 if(flags & MESHLINK_INVITE_IPV6) {
449 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
453 // Add public/canonical addresses if requested
454 if(flags & MESHLINK_INVITE_PUBLIC) {
455 // Try the CanonicalAddress first
456 char filename[PATH_MAX] = "";
457 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
458 scan_for_canonical_address(filename, &hostname[2], &port[2]);
461 if(flags & MESHLINK_INVITE_IPV4) {
462 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
465 if(flags & MESHLINK_INVITE_IPV6) {
466 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
471 for(int i = 0; i < 4; i++) {
472 // Ensure we always have a port number
473 if(hostname[i] && !port[i]) {
474 port[i] = xstrdup(mesh->myport);
478 remove_duplicate_hostnames(hostname, port, 4);
480 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
481 for(int i = 0; i < 4; i++) {
486 // Convert what we have to a sockaddr
487 struct addrinfo *ai_in, *ai_out;
488 struct addrinfo hint = {
489 .ai_family = AF_UNSPEC,
490 .ai_flags = AI_NUMERICSERV,
491 .ai_socktype = SOCK_STREAM,
493 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
499 // Convert it to a hostname
500 char resolved_host[NI_MAXHOST];
501 char resolved_port[NI_MAXSERV];
502 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
509 // Convert the hostname back to a sockaddr
510 hint.ai_family = ai_in->ai_family;
511 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
518 // Check if it's still the same sockaddr
519 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
521 freeaddrinfo(ai_out);
525 // Yes: replace the hostname with the resolved one
527 hostname[i] = xstrdup(resolved_host);
530 freeaddrinfo(ai_out);
534 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
535 remove_duplicate_hostnames(hostname, port, 4);
537 // Concatenate all unique address to the hostport string
538 for(int i = 0; i < 4; i++) {
543 // Ensure we have the same addresses in our own host config file.
545 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
546 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
549 // Append the address to the hostport string
551 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
553 hostport = newhostport;
562 static char *get_line(const char **data) {
563 if(!data || !*data) {
572 static char line[1024];
573 const char *end = strchr(*data, '\n');
574 size_t len = end ? (size_t)(end - *data) : strlen(*data);
576 if(len >= sizeof(line)) {
577 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
581 if(len && !isprint(**data)) {
585 memcpy(line, *data, len);
597 static char *get_value(const char *data, const char *var) {
598 char *line = get_line(&data);
604 char *sep = line + strcspn(line, " \t=");
605 char *val = sep + strspn(sep, " \t");
608 val += 1 + strspn(val + 1, " \t");
613 if(strcasecmp(line, var)) {
620 static bool try_bind(int port) {
621 struct addrinfo *ai = NULL;
622 struct addrinfo hint = {
623 .ai_flags = AI_PASSIVE,
624 .ai_family = AF_UNSPEC,
625 .ai_socktype = SOCK_STREAM,
626 .ai_protocol = IPPROTO_TCP,
630 snprintf(portstr, sizeof(portstr), "%d", port);
632 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
637 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
638 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
645 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
658 int check_port(meshlink_handle_t *mesh) {
659 for(int i = 0; i < 1000; i++) {
660 int port = 0x1000 + (rand() & 0x7fff);
663 char filename[PATH_MAX];
664 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
665 FILE *f = fopen(filename, "a");
668 meshlink_errno = MESHLINK_ESTORAGE;
669 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
673 fprintf(f, "Port = %d\n", port);
679 meshlink_errno = MESHLINK_ENETWORK;
680 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
684 static void deltree(const char *dirname) {
685 DIR *d = opendir(dirname);
690 while((ent = readdir(d))) {
691 if(ent->d_name[0] == '.') {
695 char filename[PATH_MAX];
696 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
698 if(unlink(filename)) {
709 static bool finalize_join(meshlink_handle_t *mesh) {
710 char *name = xstrdup(get_value(mesh->data, "Name"));
713 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
717 if(!check_id(name)) {
718 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
722 char filename[PATH_MAX];
723 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
725 FILE *f = fopen(filename, "w");
728 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
732 fprintf(f, "Name = %s\n", name);
734 // Wipe all old host config files and invitations
735 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
738 if(mkdir(filename, 0777) && errno != EEXIST) {
739 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
743 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
746 // Create a new host config file for ourself
747 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
748 FILE *fh = fopen(filename, "w");
751 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
756 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
757 // Other chunks go unfiltered to their respective host config files
758 const char *p = mesh->data;
761 while((l = get_line(&p))) {
767 // Split line into variable and value
768 int len = strcspn(l, "\t =");
770 value += strspn(value, "\t ");
774 value += strspn(value, "\t ");
780 if(!strcasecmp(l, "Name"))
781 if(strcmp(value, name)) {
785 } else if(!strcasecmp(l, "NetName")) {
789 // Check the list of known variables
793 for(i = 0; variables[i].name; i++) {
794 if(strcasecmp(l, variables[i].name)) {
802 // Ignore unknown and unsafe variables
804 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
806 } else if(!(variables[i].type & VAR_SAFE)) {
807 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
811 // Copy the safe variable to the right config file
812 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
817 while(l && !strcasecmp(l, "Name")) {
818 if(!check_id(value)) {
819 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
823 if(!strcmp(value, name)) {
824 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
828 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
829 f = fopen(filename, "w");
832 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
836 while((l = get_line(&p))) {
837 if(!strcmp(l, "#---------------------------------------------------------------#")) {
841 int len = strcspn(l, "\t =");
843 if(len == 4 && !strncasecmp(l, "Name", 4)) {
845 value += strspn(value, "\t ");
849 value += strspn(value, "\t ");
863 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
870 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
871 fprintf(fh, "Port = %s\n", mesh->myport);
875 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
879 free(mesh->self->name);
880 free(mesh->self->connection->name);
881 mesh->name = xstrdup(name);
882 mesh->self->name = xstrdup(name);
883 mesh->self->connection->name = name;
885 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
887 load_all_nodes(mesh);
892 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
894 meshlink_handle_t *mesh = handle;
895 const char *ptr = data;
898 int result = send(mesh->sock, ptr, len, 0);
900 if(result == -1 && errno == EINTR) {
902 } else if(result <= 0) {
913 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
914 meshlink_handle_t *mesh = handle;
917 case SPTPS_HANDSHAKE:
918 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
921 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
922 memcpy(mesh->data + mesh->thedatalen, msg, len);
923 mesh->thedatalen += len;
924 mesh->data[mesh->thedatalen] = 0;
928 mesh->thedatalen = 0;
929 return finalize_join(mesh);
932 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
933 shutdown(mesh->sock, SHUT_RDWR);
934 mesh->success = true;
944 static bool recvline(meshlink_handle_t *mesh, size_t len) {
945 char *newline = NULL;
951 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
952 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
954 if(result == -1 && errno == EINTR) {
956 } else if(result <= 0) {
960 mesh->blen += result;
963 if((size_t)(newline - mesh->buffer) >= len) {
967 len = newline - mesh->buffer;
969 memcpy(mesh->line, mesh->buffer, len);
971 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
972 mesh->blen -= len + 1;
976 static bool sendline(int fd, char *format, ...) {
977 static char buffer[4096];
982 va_start(ap, format);
983 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
986 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
994 int result = send(fd, p, blen, MSG_NOSIGNAL);
996 if(result == -1 && errno == EINTR) {
998 } else if(result <= 0) {
1009 static const char *errstr[] = {
1010 [MESHLINK_OK] = "No error",
1011 [MESHLINK_EINVAL] = "Invalid argument",
1012 [MESHLINK_ENOMEM] = "Out of memory",
1013 [MESHLINK_ENOENT] = "No such node",
1014 [MESHLINK_EEXIST] = "Node already exists",
1015 [MESHLINK_EINTERNAL] = "Internal error",
1016 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1017 [MESHLINK_ESTORAGE] = "Storage error",
1018 [MESHLINK_ENETWORK] = "Network error",
1019 [MESHLINK_EPEER] = "Error communicating with peer",
1020 [MESHLINK_ENOTSUP] = "Operation not supported",
1021 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1024 const char *meshlink_strerror(meshlink_errno_t err) {
1025 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1026 return "Invalid error code";
1032 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1035 char pubname[PATH_MAX], privname[PATH_MAX];
1037 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1039 if(!(key = ecdsa_generate())) {
1040 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1041 meshlink_errno = MESHLINK_EINTERNAL;
1044 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1047 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1048 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1049 meshlink_errno = MESHLINK_ESTORAGE;
1053 f = fopen(privname, "wb");
1056 meshlink_errno = MESHLINK_ESTORAGE;
1061 fchmod(fileno(f), 0600);
1064 if(!ecdsa_write_pem_private_key(key, f)) {
1065 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1068 meshlink_errno = MESHLINK_EINTERNAL;
1074 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1075 f = fopen(pubname, "a");
1078 meshlink_errno = MESHLINK_ESTORAGE;
1082 char *pubkey = ecdsa_get_base64_public_key(key);
1083 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1092 static struct timeval idle(event_loop_t *loop, void *data) {
1094 meshlink_handle_t *mesh = data;
1095 struct timeval t, tmin = {3600, 0};
1097 for splay_each(node_t, n, mesh->nodes) {
1102 t = utcp_timeout(n->utcp);
1104 if(timercmp(&t, &tmin, <)) {
1112 // Get our local address(es) by simulating connecting to an Internet host.
1113 static void add_local_addresses(meshlink_handle_t *mesh) {
1114 char host[NI_MAXHOST];
1115 char entry[MAX_STRING_SIZE];
1119 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1120 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1121 append_config_file(mesh, mesh->name, "Address", entry);
1126 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1127 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1128 append_config_file(mesh, mesh->name, "Address", entry);
1132 static bool meshlink_setup(meshlink_handle_t *mesh) {
1133 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1134 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1135 meshlink_errno = MESHLINK_ESTORAGE;
1139 char filename[PATH_MAX];
1140 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1142 if(mkdir(filename, 0777) && errno != EEXIST) {
1143 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1144 meshlink_errno = MESHLINK_ESTORAGE;
1148 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1150 if(!access(filename, F_OK)) {
1151 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1152 meshlink_errno = MESHLINK_EEXIST;
1156 FILE *f = fopen(filename, "w");
1159 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1160 meshlink_errno = MESHLINK_ESTORAGE;
1164 fprintf(f, "Name = %s\n", mesh->name);
1167 if(!ecdsa_keygen(mesh)) {
1168 meshlink_errno = MESHLINK_EINTERNAL;
1173 if(check_port(mesh) == 0) {
1174 meshlink_errno = MESHLINK_ENETWORK;
1183 static void *setup_network_in_netns_thread(void *arg) {
1184 meshlink_handle_t *mesh = arg;
1186 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1190 bool success = setup_network(mesh);
1191 add_local_addresses(mesh);
1192 return success ? arg : NULL;
1194 #endif // HAVE_SETNS
1196 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1197 if(!confbase || !*confbase) {
1198 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1199 meshlink_errno = MESHLINK_EINVAL;
1203 if(!appname || !*appname) {
1204 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1205 meshlink_errno = MESHLINK_EINVAL;
1209 if(strchr(appname, ' ')) {
1210 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1211 meshlink_errno = MESHLINK_EINVAL;
1215 if(!name || !*name) {
1216 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1218 } else { //check name only if there is a name != NULL
1219 if(!check_id(name)) {
1220 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1221 meshlink_errno = MESHLINK_EINVAL;
1226 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1227 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1228 meshlink_errno = MESHLINK_EINVAL;
1232 meshlink_open_params_t *params = xzalloc(sizeof * params);
1234 params->confbase = xstrdup(confbase);
1235 params->name = xstrdup(name);
1236 params->appname = xstrdup(appname);
1237 params->devclass = devclass;
1243 void meshlink_open_params_free(meshlink_open_params_t *params) {
1245 meshlink_errno = MESHLINK_EINVAL;
1249 free(params->confbase);
1251 free(params->appname);
1256 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1257 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1258 meshlink_open_params_t params;
1259 memset(¶ms, 0, sizeof(params));
1261 params.confbase = (char *)confbase;
1262 params.name = (char *)name;
1263 params.appname = (char *)appname;
1264 params.devclass = devclass;
1267 return meshlink_open_ex(¶ms);
1269 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1270 // Validate arguments provided by the application
1271 bool usingname = false;
1273 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1275 if(!params->confbase || !*params->confbase) {
1276 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1277 meshlink_errno = MESHLINK_EINVAL;
1281 if(!params->appname || !*params->appname) {
1282 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1283 meshlink_errno = MESHLINK_EINVAL;
1287 if(strchr(params->appname, ' ')) {
1288 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1289 meshlink_errno = MESHLINK_EINVAL;
1293 if(!params->name || !*params->name) {
1294 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1296 } else { //check name only if there is a name != NULL
1298 if(!check_id(params->name)) {
1299 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1300 meshlink_errno = MESHLINK_EINVAL;
1307 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1308 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1309 meshlink_errno = MESHLINK_EINVAL;
1313 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1314 mesh->confbase = xstrdup(params->confbase);
1315 mesh->appname = xstrdup(params->appname);
1316 mesh->devclass = params->devclass;
1317 mesh->discovery = true;
1318 mesh->invitation_timeout = 604800; // 1 week
1319 mesh->netns = params->netns;
1320 mesh->submeshes = NULL;
1323 mesh->name = xstrdup(params->name);
1327 pthread_mutexattr_t attr;
1328 pthread_mutexattr_init(&attr);
1329 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1330 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1332 mesh->threadstarted = false;
1333 event_loop_init(&mesh->loop);
1334 mesh->loop.data = mesh;
1336 meshlink_queue_init(&mesh->outpacketqueue);
1338 // Check whether meshlink.conf already exists
1340 char filename[PATH_MAX];
1341 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1343 if(access(filename, R_OK)) {
1344 if(errno == ENOENT) {
1345 // If not, create it
1346 if(!meshlink_setup(mesh)) {
1347 // meshlink_errno is set by meshlink_setup()
1351 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1352 meshlink_close(mesh);
1353 meshlink_errno = MESHLINK_ESTORAGE;
1358 // Open the configuration file and lock it
1360 mesh->conffile = fopen(filename, "r");
1362 if(!mesh->conffile) {
1363 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1364 meshlink_close(mesh);
1365 meshlink_errno = MESHLINK_ESTORAGE;
1370 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1374 // TODO: use _locking()?
1377 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1378 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1379 meshlink_close(mesh);
1380 meshlink_errno = MESHLINK_EBUSY;
1386 // Read the configuration
1388 init_configuration(&mesh->config);
1390 if(!read_server_config(mesh)) {
1391 meshlink_close(mesh);
1392 meshlink_errno = MESHLINK_ESTORAGE;
1397 struct WSAData wsa_state;
1399 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1403 // Setup up everything
1404 // TODO: we should not open listening sockets yet
1406 bool success = false;
1408 if(mesh->netns != -1) {
1412 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1413 void *retval = NULL;
1414 success = pthread_join(thr, &retval) == 0 && retval;
1418 meshlink_errno = MESHLINK_EINTERNAL;
1421 #endif // HAVE_SETNS
1423 success = setup_network(mesh);
1424 add_local_addresses(mesh);
1428 meshlink_close(mesh);
1429 meshlink_errno = MESHLINK_ENETWORK;
1433 idle_set(&mesh->loop, idle, mesh);
1435 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1439 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1440 meshlink_submesh_t *s = NULL;
1443 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1444 meshlink_errno = MESHLINK_EINVAL;
1448 if(!submesh || !*submesh) {
1449 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1450 meshlink_errno = MESHLINK_EINVAL;
1455 pthread_mutex_lock(&(mesh->mesh_mutex));
1457 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1459 pthread_mutex_unlock(&(mesh->mesh_mutex));
1464 static void *meshlink_main_loop(void *arg) {
1465 meshlink_handle_t *mesh = arg;
1467 if(mesh->netns != -1) {
1470 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1476 #endif // HAVE_SETNS
1479 pthread_mutex_lock(&(mesh->mesh_mutex));
1481 try_outgoing_connections(mesh);
1483 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1485 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1487 pthread_mutex_unlock(&(mesh->mesh_mutex));
1491 bool meshlink_start(meshlink_handle_t *mesh) {
1493 meshlink_errno = MESHLINK_EINVAL;
1497 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1499 pthread_mutex_lock(&(mesh->mesh_mutex));
1501 if(mesh->threadstarted) {
1502 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1503 pthread_mutex_unlock(&(mesh->mesh_mutex));
1507 if(mesh->listen_socket[0].tcp.fd < 0) {
1508 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1509 meshlink_errno = MESHLINK_ENETWORK;
1513 mesh->thedatalen = 0;
1515 // TODO: open listening sockets first
1517 //Check that a valid name is set
1519 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1520 meshlink_errno = MESHLINK_EINVAL;
1521 pthread_mutex_unlock(&(mesh->mesh_mutex));
1525 // Start the main thread
1527 event_loop_start(&mesh->loop);
1529 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1530 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1531 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1532 meshlink_errno = MESHLINK_EINTERNAL;
1533 event_loop_stop(&mesh->loop);
1534 pthread_mutex_unlock(&(mesh->mesh_mutex));
1538 mesh->threadstarted = true;
1542 if(mesh->discovery) {
1543 discovery_start(mesh);
1548 pthread_mutex_unlock(&(mesh->mesh_mutex));
1552 void meshlink_stop(meshlink_handle_t *mesh) {
1554 meshlink_errno = MESHLINK_EINVAL;
1558 pthread_mutex_lock(&(mesh->mesh_mutex));
1559 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1564 if(mesh->discovery) {
1565 discovery_stop(mesh);
1570 // Shut down the main thread
1571 event_loop_stop(&mesh->loop);
1573 // Send ourselves a UDP packet to kick the event loop
1574 for(int i = 0; i < mesh->listen_sockets; i++) {
1576 socklen_t salen = sizeof(sa.sa);
1578 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1579 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1583 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1584 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1588 if(mesh->threadstarted) {
1589 // Wait for the main thread to finish
1590 pthread_mutex_unlock(&(mesh->mesh_mutex));
1591 pthread_join(mesh->thread, NULL);
1592 pthread_mutex_lock(&(mesh->mesh_mutex));
1594 mesh->threadstarted = false;
1597 // Close all metaconnections
1598 if(mesh->connections) {
1599 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1601 connection_t *c = node->data;
1603 terminate_connection(mesh, c, false);
1607 if(mesh->outgoings) {
1608 list_delete_list(mesh->outgoings);
1609 mesh->outgoings = NULL;
1612 pthread_mutex_unlock(&(mesh->mesh_mutex));
1615 void meshlink_close(meshlink_handle_t *mesh) {
1616 if(!mesh || !mesh->confbase) {
1617 meshlink_errno = MESHLINK_EINVAL;
1621 // stop can be called even if mesh has not been started
1622 meshlink_stop(mesh);
1624 // lock is not released after this
1625 pthread_mutex_lock(&(mesh->mesh_mutex));
1627 // Close and free all resources used.
1629 close_network_connections(mesh);
1631 logger(mesh, MESHLINK_INFO, "Terminating");
1633 exit_configuration(&mesh->config);
1634 event_loop_exit(&mesh->loop);
1638 if(mesh->confbase) {
1644 ecdsa_free(mesh->invitation_key);
1646 if(mesh->netns != -1) {
1651 free(mesh->appname);
1652 free(mesh->confbase);
1653 pthread_mutex_destroy(&(mesh->mesh_mutex));
1655 if(mesh->conffile) {
1656 fclose(mesh->conffile);
1659 memset(mesh, 0, sizeof(*mesh));
1664 bool meshlink_destroy(const char *confbase) {
1666 meshlink_errno = MESHLINK_EINVAL;
1670 char filename[PATH_MAX];
1671 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1673 if(unlink(filename)) {
1674 if(errno == ENOENT) {
1675 meshlink_errno = MESHLINK_ENOENT;
1678 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1679 meshlink_errno = MESHLINK_ESTORAGE;
1689 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1691 meshlink_errno = MESHLINK_EINVAL;
1695 pthread_mutex_lock(&(mesh->mesh_mutex));
1696 mesh->receive_cb = cb;
1697 pthread_mutex_unlock(&(mesh->mesh_mutex));
1700 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1702 meshlink_errno = MESHLINK_EINVAL;
1706 pthread_mutex_lock(&(mesh->mesh_mutex));
1707 mesh->connection_try_cb = cb;
1708 pthread_mutex_unlock(&(mesh->mesh_mutex));
1711 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1713 meshlink_errno = MESHLINK_EINVAL;
1717 pthread_mutex_lock(&(mesh->mesh_mutex));
1718 mesh->node_status_cb = cb;
1719 pthread_mutex_unlock(&(mesh->mesh_mutex));
1722 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1724 meshlink_errno = MESHLINK_EINVAL;
1728 pthread_mutex_lock(&(mesh->mesh_mutex));
1729 mesh->node_duplicate_cb = cb;
1730 pthread_mutex_unlock(&(mesh->mesh_mutex));
1733 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1735 pthread_mutex_lock(&(mesh->mesh_mutex));
1737 mesh->log_level = cb ? level : 0;
1738 pthread_mutex_unlock(&(mesh->mesh_mutex));
1741 global_log_level = cb ? level : 0;
1745 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1746 meshlink_packethdr_t *hdr;
1748 // Validate arguments
1749 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1750 meshlink_errno = MESHLINK_EINVAL;
1759 meshlink_errno = MESHLINK_EINVAL;
1763 node_t *n = (node_t *)destination;
1765 if(n->status.blacklisted) {
1766 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1770 // Prepare the packet
1771 vpn_packet_t *packet = malloc(sizeof(*packet));
1774 meshlink_errno = MESHLINK_ENOMEM;
1778 packet->probe = false;
1779 packet->tcp = false;
1780 packet->len = len + sizeof(*hdr);
1782 hdr = (meshlink_packethdr_t *)packet->data;
1783 memset(hdr, 0, sizeof(*hdr));
1784 // leave the last byte as 0 to make sure strings are always
1785 // null-terminated if they are longer than the buffer
1786 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1787 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1789 memcpy(packet->data + sizeof(*hdr), data, len);
1792 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1794 meshlink_errno = MESHLINK_ENOMEM;
1798 // Notify event loop
1799 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1804 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1806 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1812 mesh->self->in_packets++;
1813 mesh->self->in_bytes += packet->len;
1814 route(mesh, mesh->self, packet);
1817 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1818 if(!mesh || !destination) {
1819 meshlink_errno = MESHLINK_EINVAL;
1823 pthread_mutex_lock(&(mesh->mesh_mutex));
1825 node_t *n = (node_t *)destination;
1827 if(!n->status.reachable) {
1828 pthread_mutex_unlock(&(mesh->mesh_mutex));
1831 } else if(n->mtuprobes > 30 && n->minmtu) {
1832 pthread_mutex_unlock(&(mesh->mesh_mutex));
1835 pthread_mutex_unlock(&(mesh->mesh_mutex));
1840 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1841 if(!mesh || !node) {
1842 meshlink_errno = MESHLINK_EINVAL;
1846 pthread_mutex_lock(&(mesh->mesh_mutex));
1848 node_t *n = (node_t *)node;
1850 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1851 meshlink_errno = MESHLINK_EINTERNAL;
1852 pthread_mutex_unlock(&(mesh->mesh_mutex));
1856 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1859 meshlink_errno = MESHLINK_EINTERNAL;
1862 pthread_mutex_unlock(&(mesh->mesh_mutex));
1866 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1868 meshlink_errno = MESHLINK_EINVAL;
1872 return (meshlink_node_t *)mesh->self;
1875 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1876 if(!mesh || !name) {
1877 meshlink_errno = MESHLINK_EINVAL;
1881 meshlink_node_t *node = NULL;
1883 pthread_mutex_lock(&(mesh->mesh_mutex));
1884 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1885 pthread_mutex_unlock(&(mesh->mesh_mutex));
1889 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1890 if(!mesh || !name) {
1891 meshlink_errno = MESHLINK_EINVAL;
1895 meshlink_submesh_t *submesh = NULL;
1897 pthread_mutex_lock(&(mesh->mesh_mutex));
1898 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1899 pthread_mutex_unlock(&(mesh->mesh_mutex));
1903 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1904 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1905 meshlink_errno = MESHLINK_EINVAL;
1909 meshlink_node_t **result;
1912 pthread_mutex_lock(&(mesh->mesh_mutex));
1914 *nmemb = mesh->nodes->count;
1915 result = realloc(nodes, *nmemb * sizeof(*nodes));
1918 meshlink_node_t **p = result;
1920 for splay_each(node_t, n, mesh->nodes) {
1921 *p++ = (meshlink_node_t *)n;
1926 meshlink_errno = MESHLINK_ENOMEM;
1929 pthread_mutex_unlock(&(mesh->mesh_mutex));
1934 static meshlink_node_t **meshlink_get_all_nodes_by_condition(meshlink_handle_t *mesh, const void *condition, meshlink_node_t **nodes, size_t *nmemb, search_node_by_condition_t search_node) {
1935 meshlink_node_t **result;
1937 pthread_mutex_lock(&(mesh->mesh_mutex));
1941 for splay_each(node_t, n, mesh->nodes) {
1942 if(true == search_node(n, condition)) {
1943 *nmemb = *nmemb + 1;
1949 pthread_mutex_unlock(&(mesh->mesh_mutex));
1953 result = realloc(nodes, *nmemb * sizeof(*nodes));
1956 meshlink_node_t **p = result;
1958 for splay_each(node_t, n, mesh->nodes) {
1959 if(true == search_node(n, condition)) {
1960 *p++ = (meshlink_node_t *)n;
1966 meshlink_errno = MESHLINK_ENOMEM;
1969 pthread_mutex_unlock(&(mesh->mesh_mutex));
1974 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1975 dev_class_t *devclass = (dev_class_t *)condition;
1977 if(*devclass == node->devclass) {
1984 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1985 if(condition == node->submesh) {
1992 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) {
1993 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1994 meshlink_errno = MESHLINK_EINVAL;
1998 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2001 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2002 if(!mesh || !submesh || !nmemb) {
2003 meshlink_errno = MESHLINK_EINVAL;
2007 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2010 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2011 if(!mesh || !node) {
2012 meshlink_errno = MESHLINK_EINVAL;
2016 dev_class_t devclass;
2018 pthread_mutex_lock(&(mesh->mesh_mutex));
2020 devclass = ((node_t *)node)->devclass;
2022 pthread_mutex_unlock(&(mesh->mesh_mutex));
2027 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2028 if(!mesh || !node) {
2029 meshlink_errno = MESHLINK_EINVAL;
2033 node_t *n = (node_t *)node;
2035 meshlink_submesh_t *s;
2037 s = (meshlink_submesh_t *)n->submesh;
2042 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2043 if(!mesh || !data || !len || !signature || !siglen) {
2044 meshlink_errno = MESHLINK_EINVAL;
2048 if(*siglen < MESHLINK_SIGLEN) {
2049 meshlink_errno = MESHLINK_EINVAL;
2053 pthread_mutex_lock(&(mesh->mesh_mutex));
2055 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
2056 meshlink_errno = MESHLINK_EINTERNAL;
2057 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 *siglen = MESHLINK_SIGLEN;
2062 pthread_mutex_unlock(&(mesh->mesh_mutex));
2066 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2067 if(!mesh || !data || !len || !signature) {
2068 meshlink_errno = MESHLINK_EINVAL;
2072 if(siglen != MESHLINK_SIGLEN) {
2073 meshlink_errno = MESHLINK_EINVAL;
2077 pthread_mutex_lock(&(mesh->mesh_mutex));
2081 struct node_t *n = (struct node_t *)source;
2082 node_read_ecdsa_public_key(mesh, n);
2085 meshlink_errno = MESHLINK_EINTERNAL;
2088 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2091 pthread_mutex_unlock(&(mesh->mesh_mutex));
2095 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2096 char filename[PATH_MAX];
2098 pthread_mutex_lock(&(mesh->mesh_mutex));
2100 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2102 if(mkdir(filename, 0700) && errno != EEXIST) {
2103 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2104 meshlink_errno = MESHLINK_ESTORAGE;
2105 pthread_mutex_unlock(&(mesh->mesh_mutex));
2109 // Count the number of valid invitations, clean up old ones
2110 DIR *dir = opendir(filename);
2113 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2114 meshlink_errno = MESHLINK_ESTORAGE;
2115 pthread_mutex_unlock(&(mesh->mesh_mutex));
2122 time_t deadline = time(NULL) - 604800; // 1 week in the past
2124 while((ent = readdir(dir))) {
2125 if(strlen(ent->d_name) != 24) {
2129 char invname[PATH_MAX];
2132 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2133 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2137 if(!stat(invname, &st)) {
2138 if(mesh->invitation_key && deadline < (time_t)st.st_mtime) {
2144 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2150 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2152 meshlink_errno = MESHLINK_ESTORAGE;
2153 pthread_mutex_unlock(&(mesh->mesh_mutex));
2159 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2161 // Remove the key if there are no outstanding invitations.
2165 if(mesh->invitation_key) {
2166 ecdsa_free(mesh->invitation_key);
2167 mesh->invitation_key = NULL;
2171 if(mesh->invitation_key) {
2172 pthread_mutex_unlock(&(mesh->mesh_mutex));
2176 // Create a new key if necessary.
2177 FILE *f = fopen(filename, "rb");
2180 if(errno != ENOENT) {
2181 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2182 meshlink_errno = MESHLINK_ESTORAGE;
2183 pthread_mutex_unlock(&(mesh->mesh_mutex));
2187 mesh->invitation_key = ecdsa_generate();
2189 if(!mesh->invitation_key) {
2190 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2191 meshlink_errno = MESHLINK_EINTERNAL;
2192 pthread_mutex_unlock(&(mesh->mesh_mutex));
2196 f = fopen(filename, "wb");
2199 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2200 meshlink_errno = MESHLINK_ESTORAGE;
2201 pthread_mutex_unlock(&(mesh->mesh_mutex));
2205 chmod(filename, 0600);
2206 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2209 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2212 if(!mesh->invitation_key) {
2213 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2214 meshlink_errno = MESHLINK_ESTORAGE;
2218 pthread_mutex_unlock(&(mesh->mesh_mutex));
2219 return mesh->invitation_key;
2222 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2223 if(!mesh || !node || !address) {
2224 meshlink_errno = MESHLINK_EINVAL;
2228 if(!is_valid_hostname(address)) {
2229 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2230 meshlink_errno = MESHLINK_EINVAL;
2234 if(port && !is_valid_port(port)) {
2235 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2236 meshlink_errno = MESHLINK_EINVAL;
2240 char *canonical_address;
2243 xasprintf(&canonical_address, "%s %s", address, port);
2245 canonical_address = xstrdup(address);
2248 pthread_mutex_lock(&(mesh->mesh_mutex));
2249 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2250 pthread_mutex_unlock(&(mesh->mesh_mutex));
2252 free(canonical_address);
2256 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2257 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2260 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2262 meshlink_errno = MESHLINK_EINVAL;
2266 char *address = meshlink_get_external_address(mesh);
2274 pthread_mutex_lock(&(mesh->mesh_mutex));
2275 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2276 pthread_mutex_unlock(&(mesh->mesh_mutex));
2282 int meshlink_get_port(meshlink_handle_t *mesh) {
2284 meshlink_errno = MESHLINK_EINVAL;
2289 meshlink_errno = MESHLINK_EINTERNAL;
2293 return atoi(mesh->myport);
2296 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2297 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2298 meshlink_errno = MESHLINK_EINVAL;
2302 if(mesh->myport && port == atoi(mesh->myport)) {
2306 if(!try_bind(port)) {
2307 meshlink_errno = MESHLINK_ENETWORK;
2313 pthread_mutex_lock(&(mesh->mesh_mutex));
2315 if(mesh->threadstarted) {
2316 meshlink_errno = MESHLINK_EINVAL;
2320 close_network_connections(mesh);
2321 exit_configuration(&mesh->config);
2324 snprintf(portstr, sizeof(portstr), "%d", port);
2325 portstr[sizeof(portstr) - 1] = 0;
2327 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2329 init_configuration(&mesh->config);
2331 if(!read_server_config(mesh)) {
2332 meshlink_errno = MESHLINK_ESTORAGE;
2333 } else if(!setup_network(mesh)) {
2334 meshlink_errno = MESHLINK_ENETWORK;
2340 pthread_mutex_unlock(&(mesh->mesh_mutex));
2345 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2346 mesh->invitation_timeout = timeout;
2349 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2350 meshlink_submesh_t *s = NULL;
2353 meshlink_errno = MESHLINK_EINVAL;
2358 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2361 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2362 meshlink_errno = MESHLINK_EINVAL;
2366 s = (meshlink_submesh_t *)mesh->self->submesh;
2369 pthread_mutex_lock(&(mesh->mesh_mutex));
2371 // Check validity of the new node's name
2372 if(!check_id(name)) {
2373 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2374 meshlink_errno = MESHLINK_EINVAL;
2375 pthread_mutex_unlock(&(mesh->mesh_mutex));
2379 // Ensure no host configuration file with that name exists
2380 char filename[PATH_MAX];
2381 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2383 if(!access(filename, F_OK)) {
2384 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2385 meshlink_errno = MESHLINK_EEXIST;
2386 pthread_mutex_unlock(&(mesh->mesh_mutex));
2390 // Ensure no other nodes know about this name
2391 if(meshlink_get_node(mesh, name)) {
2392 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2393 meshlink_errno = MESHLINK_EEXIST;
2394 pthread_mutex_unlock(&(mesh->mesh_mutex));
2398 // Get the local address
2399 char *address = get_my_hostname(mesh, flags);
2402 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2403 meshlink_errno = MESHLINK_ERESOLV;
2404 pthread_mutex_unlock(&(mesh->mesh_mutex));
2408 if(!refresh_invitation_key(mesh)) {
2409 meshlink_errno = MESHLINK_EINTERNAL;
2410 pthread_mutex_unlock(&(mesh->mesh_mutex));
2416 // Create a hash of the key.
2417 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2418 sha512(fingerprint, strlen(fingerprint), hash);
2419 b64encode_urlsafe(hash, hash, 18);
2421 // Create a random cookie for this invitation.
2423 randomize(cookie, 18);
2425 // Create a filename that doesn't reveal the cookie itself
2426 char buf[18 + strlen(fingerprint)];
2427 char cookiehash[64];
2428 memcpy(buf, cookie, 18);
2429 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2430 sha512(buf, sizeof(buf), cookiehash);
2431 b64encode_urlsafe(cookiehash, cookiehash, 18);
2433 b64encode_urlsafe(cookie, cookie, 18);
2437 // Create a file containing the details of the invitation.
2438 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2439 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2442 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2443 meshlink_errno = MESHLINK_ESTORAGE;
2444 pthread_mutex_unlock(&(mesh->mesh_mutex));
2448 FILE *f = fdopen(ifd, "w");
2454 // Fill in the details.
2455 fprintf(f, "Name = %s\n", name);
2458 fprintf(f, "SubMesh = %s\n", s->name);
2461 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2463 // Copy Broadcast and Mode
2464 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2465 FILE *tc = fopen(filename, "r");
2470 while(fgets(buf, sizeof(buf), tc)) {
2471 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2472 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2475 // Make sure there is a newline character.
2476 if(!strchr(buf, '\n')) {
2484 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2485 meshlink_errno = MESHLINK_ESTORAGE;
2486 pthread_mutex_unlock(&(mesh->mesh_mutex));
2490 fprintf(f, "#---------------------------------------------------------------#\n");
2491 fprintf(f, "Name = %s\n", mesh->self->name);
2493 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2497 // Create an URL from the local address, key hash and cookie
2499 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2502 pthread_mutex_unlock(&(mesh->mesh_mutex));
2506 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2507 return meshlink_invite_ex(mesh, submesh, name, 0);
2510 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2511 if(!mesh || !invitation) {
2512 meshlink_errno = MESHLINK_EINVAL;
2516 pthread_mutex_lock(&(mesh->mesh_mutex));
2518 //Before doing meshlink_join make sure we are not connected to another mesh
2519 if(mesh->threadstarted) {
2520 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2521 meshlink_errno = MESHLINK_EINVAL;
2522 pthread_mutex_unlock(&(mesh->mesh_mutex));
2526 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2527 char copy[strlen(invitation) + 1];
2528 strcpy(copy, invitation);
2530 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2532 char *slash = strchr(copy, '/');
2540 if(strlen(slash) != 48) {
2544 char *address = copy;
2547 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2551 // Generate a throw-away key for the invitation.
2552 ecdsa_t *key = ecdsa_generate();
2555 meshlink_errno = MESHLINK_EINTERNAL;
2556 pthread_mutex_unlock(&(mesh->mesh_mutex));
2560 char *b64key = ecdsa_get_base64_public_key(key);
2564 while(address && *address) {
2565 // We allow commas in the address part to support multiple addresses in one invitation URL.
2566 comma = strchr(address, ',');
2572 // Split of the port
2573 port = strrchr(address, ':');
2581 // IPv6 address are enclosed in brackets, per RFC 3986
2582 if(*address == '[') {
2584 char *bracket = strchr(address, ']');
2597 // Connect to the meshlink daemon mentioned in the URL.
2598 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2601 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2602 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2604 if(mesh->sock == -1) {
2605 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2606 meshlink_errno = MESHLINK_ENETWORK;
2610 set_timeout(mesh->sock, 5000);
2612 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2613 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2614 meshlink_errno = MESHLINK_ENETWORK;
2615 closesocket(mesh->sock);
2623 meshlink_errno = MESHLINK_ERESOLV;
2626 if(mesh->sock != -1 || !comma) {
2633 if(mesh->sock == -1) {
2634 pthread_mutex_unlock(&mesh->mesh_mutex);
2638 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2640 // Tell him we have an invitation, and give him our throw-away key.
2644 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2645 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2646 closesocket(mesh->sock);
2647 meshlink_errno = MESHLINK_ENETWORK;
2648 pthread_mutex_unlock(&(mesh->mesh_mutex));
2654 char hisname[4096] = "";
2655 int code, hismajor, hisminor = 0;
2657 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) {
2658 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2659 closesocket(mesh->sock);
2660 meshlink_errno = MESHLINK_ENETWORK;
2661 pthread_mutex_unlock(&(mesh->mesh_mutex));
2665 // Check if the hash of the key he gave us matches the hash in the URL.
2666 char *fingerprint = mesh->line + 2;
2669 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2670 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2671 meshlink_errno = MESHLINK_EINTERNAL;
2672 pthread_mutex_unlock(&(mesh->mesh_mutex));
2676 if(memcmp(hishash, mesh->hash, 18)) {
2677 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2678 meshlink_errno = MESHLINK_EPEER;
2679 pthread_mutex_unlock(&(mesh->mesh_mutex));
2684 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2687 meshlink_errno = MESHLINK_EINTERNAL;
2688 pthread_mutex_unlock(&(mesh->mesh_mutex));
2692 // Start an SPTPS session
2693 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2694 meshlink_errno = MESHLINK_EINTERNAL;
2695 pthread_mutex_unlock(&(mesh->mesh_mutex));
2699 // Feed rest of input buffer to SPTPS
2700 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2701 meshlink_errno = MESHLINK_EPEER;
2702 pthread_mutex_unlock(&(mesh->mesh_mutex));
2708 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2710 if(errno == EINTR) {
2714 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2715 meshlink_errno = MESHLINK_ENETWORK;
2716 pthread_mutex_unlock(&(mesh->mesh_mutex));
2720 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2721 meshlink_errno = MESHLINK_EPEER;
2722 pthread_mutex_unlock(&(mesh->mesh_mutex));
2727 sptps_stop(&mesh->sptps);
2730 closesocket(mesh->sock);
2732 if(!mesh->success) {
2733 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2734 meshlink_errno = MESHLINK_EPEER;
2735 pthread_mutex_unlock(&(mesh->mesh_mutex));
2739 pthread_mutex_unlock(&(mesh->mesh_mutex));
2743 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2744 meshlink_errno = MESHLINK_EINVAL;
2745 pthread_mutex_unlock(&(mesh->mesh_mutex));
2749 char *meshlink_export(meshlink_handle_t *mesh) {
2751 meshlink_errno = MESHLINK_EINVAL;
2755 pthread_mutex_lock(&(mesh->mesh_mutex));
2757 char filename[PATH_MAX];
2758 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2759 FILE *f = fopen(filename, "r");
2762 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2763 meshlink_errno = MESHLINK_ESTORAGE;
2764 pthread_mutex_unlock(&(mesh->mesh_mutex));
2768 fseek(f, 0, SEEK_END);
2769 int fsize = ftell(f);
2772 size_t len = fsize + 9 + strlen(mesh->self->name);
2773 char *buf = xmalloc(len);
2774 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2776 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2777 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2780 meshlink_errno = MESHLINK_ESTORAGE;
2781 pthread_mutex_unlock(&(mesh->mesh_mutex));
2788 pthread_mutex_unlock(&(mesh->mesh_mutex));
2792 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2793 if(!mesh || !data) {
2794 meshlink_errno = MESHLINK_EINVAL;
2798 pthread_mutex_lock(&(mesh->mesh_mutex));
2800 if(strncmp(data, "Name = ", 7)) {
2801 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2802 meshlink_errno = MESHLINK_EPEER;
2803 pthread_mutex_unlock(&(mesh->mesh_mutex));
2807 char *end = strchr(data + 7, '\n');
2810 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2811 meshlink_errno = MESHLINK_EPEER;
2812 pthread_mutex_unlock(&(mesh->mesh_mutex));
2816 int len = end - (data + 7);
2818 memcpy(name, data + 7, len);
2821 if(!check_id(name)) {
2822 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2823 meshlink_errno = MESHLINK_EPEER;
2824 pthread_mutex_unlock(&(mesh->mesh_mutex));
2828 char filename[PATH_MAX];
2829 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2831 if(!access(filename, F_OK)) {
2832 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2833 meshlink_errno = MESHLINK_EEXIST;
2834 pthread_mutex_unlock(&(mesh->mesh_mutex));
2838 if(errno != ENOENT) {
2839 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2840 meshlink_errno = MESHLINK_ESTORAGE;
2841 pthread_mutex_unlock(&(mesh->mesh_mutex));
2845 FILE *f = fopen(filename, "w");
2848 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2849 meshlink_errno = MESHLINK_ESTORAGE;
2850 pthread_mutex_unlock(&(mesh->mesh_mutex));
2854 fwrite(end + 1, strlen(end + 1), 1, f);
2857 load_all_nodes(mesh);
2859 pthread_mutex_unlock(&(mesh->mesh_mutex));
2863 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2864 if(!mesh || !node) {
2865 meshlink_errno = MESHLINK_EINVAL;
2869 pthread_mutex_lock(&(mesh->mesh_mutex));
2874 if(n == mesh->self) {
2875 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2876 meshlink_errno = MESHLINK_EINVAL;
2877 pthread_mutex_unlock(&(mesh->mesh_mutex));
2881 if(n->status.blacklisted) {
2882 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2883 pthread_mutex_unlock(&(mesh->mesh_mutex));
2887 n->status.blacklisted = true;
2888 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2890 //Make blacklisting persistent in the config file
2891 append_config_file(mesh, n->name, "blacklisted", "yes");
2893 //Immediately terminate any connections we have with the blacklisted node
2894 for list_each(connection_t, c, mesh->connections) {
2896 terminate_connection(mesh, c, c->status.active);
2900 utcp_abort_all_connections(n->utcp);
2906 n->status.udp_confirmed = false;
2908 if(n->status.reachable) {
2909 update_node_status(mesh, n);
2912 pthread_mutex_unlock(&(mesh->mesh_mutex));
2915 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2916 if(!mesh || !node) {
2917 meshlink_errno = MESHLINK_EINVAL;
2921 pthread_mutex_lock(&(mesh->mesh_mutex));
2923 node_t *n = (node_t *)node;
2925 if(!n->status.blacklisted) {
2926 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2927 meshlink_errno = MESHLINK_EINVAL;
2928 pthread_mutex_unlock(&(mesh->mesh_mutex));
2932 n->status.blacklisted = false;
2934 if(n->status.reachable) {
2935 update_node_status(mesh, n);
2938 //Remove blacklisting from the config file
2939 append_config_file(mesh, n->name, "blacklisted", NULL);
2941 pthread_mutex_unlock(&(mesh->mesh_mutex));
2945 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2946 mesh->default_blacklist = blacklist;
2949 /* Hint that a hostname may be found at an address
2950 * See header file for detailed comment.
2952 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2953 if(!mesh || !node || !addr) {
2957 // Ignore hints about ourself.
2958 if((node_t *)node == mesh->self) {
2962 pthread_mutex_lock(&(mesh->mesh_mutex));
2964 char *host = NULL, *port = NULL, *str = NULL;
2965 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2968 xasprintf(&str, "%s %s", host, port);
2970 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2971 modify_config_file(mesh, node->name, "Address", str, 5);
2973 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2981 pthread_mutex_unlock(&(mesh->mesh_mutex));
2982 // @TODO do we want to fire off a connection attempt right away?
2985 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2987 node_t *n = utcp->priv;
2988 meshlink_handle_t *mesh = n->mesh;
2989 return mesh->channel_accept_cb;
2992 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2993 meshlink_channel_t *channel = connection->priv;
2999 node_t *n = channel->node;
3000 meshlink_handle_t *mesh = n->mesh;
3002 if(n->status.destroyed) {
3003 meshlink_channel_close(mesh, channel);
3004 } else if(channel->receive_cb) {
3005 channel->receive_cb(mesh, channel, data, len);
3011 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3012 node_t *n = utcp_connection->utcp->priv;
3018 meshlink_handle_t *mesh = n->mesh;
3020 if(!mesh->channel_accept_cb) {
3024 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3026 channel->c = utcp_connection;
3028 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3029 utcp_accept(utcp_connection, channel_recv, channel);
3035 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3036 node_t *n = utcp->priv;
3038 if(n->status.destroyed) {
3042 meshlink_handle_t *mesh = n->mesh;
3043 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3046 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3047 if(!mesh || !channel) {
3048 meshlink_errno = MESHLINK_EINVAL;
3052 channel->receive_cb = cb;
3055 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3057 node_t *n = (node_t *)source;
3063 utcp_recv(n->utcp, data, len);
3066 static void channel_poll(struct utcp_connection *connection, size_t len) {
3067 meshlink_channel_t *channel = connection->priv;
3073 node_t *n = channel->node;
3074 meshlink_handle_t *mesh = n->mesh;
3076 if(channel->poll_cb) {
3077 channel->poll_cb(mesh, channel, len);
3081 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3083 channel->poll_cb = cb;
3084 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
3087 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3089 meshlink_errno = MESHLINK_EINVAL;
3093 pthread_mutex_lock(&mesh->mesh_mutex);
3094 mesh->channel_accept_cb = cb;
3095 mesh->receive_cb = channel_receive;
3097 for splay_each(node_t, n, mesh->nodes) {
3098 if(!n->utcp && n != mesh->self) {
3099 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3103 pthread_mutex_unlock(&mesh->mesh_mutex);
3106 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) {
3108 abort(); // TODO: handle non-NULL data
3111 if(!mesh || !node) {
3112 meshlink_errno = MESHLINK_EINVAL;
3116 node_t *n = (node_t *)node;
3119 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3120 mesh->receive_cb = channel_receive;
3123 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3128 if(n->status.blacklisted) {
3129 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3133 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3135 channel->receive_cb = cb;
3136 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3139 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3147 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) {
3148 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3151 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3152 if(!mesh || !channel) {
3153 meshlink_errno = MESHLINK_EINVAL;
3157 utcp_shutdown(channel->c, direction);
3160 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3161 if(!mesh || !channel) {
3162 meshlink_errno = MESHLINK_EINVAL;
3166 utcp_close(channel->c);
3170 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3171 if(!mesh || !channel) {
3172 meshlink_errno = MESHLINK_EINVAL;
3181 meshlink_errno = MESHLINK_EINVAL;
3185 // TODO: more finegrained locking.
3186 // Ideally we want to put the data into the UTCP connection's send buffer.
3187 // Then, preferably only if there is room in the receiver window,
3188 // kick the meshlink thread to go send packets.
3190 pthread_mutex_lock(&mesh->mesh_mutex);
3191 ssize_t retval = utcp_send(channel->c, data, len);
3192 pthread_mutex_unlock(&mesh->mesh_mutex);
3195 meshlink_errno = MESHLINK_ENETWORK;
3201 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3202 if(!mesh || !channel) {
3203 meshlink_errno = MESHLINK_EINVAL;
3207 return channel->c->flags;
3210 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3211 if(!mesh || !channel) {
3212 meshlink_errno = MESHLINK_EINVAL;
3216 return utcp_get_sendq(channel->c);
3219 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3220 if(!mesh || !channel) {
3221 meshlink_errno = MESHLINK_EINVAL;
3225 return utcp_get_recvq(channel->c);
3228 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3229 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3230 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3233 if(mesh->node_status_cb) {
3234 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3238 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3239 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3243 n->status.duplicate = true;
3244 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3247 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3251 meshlink_errno = MESHLINK_EINVAL;
3255 pthread_mutex_lock(&mesh->mesh_mutex);
3257 if(mesh->discovery == enable) {
3261 if(mesh->threadstarted) {
3263 discovery_start(mesh);
3265 discovery_stop(mesh);
3269 mesh->discovery = enable;
3272 pthread_mutex_unlock(&mesh->mesh_mutex);
3276 meshlink_errno = MESHLINK_ENOTSUP;
3280 static void __attribute__((constructor)) meshlink_init(void) {
3283 randomize(&seed, sizeof(seed));
3287 static void __attribute__((destructor)) meshlink_exit(void) {
3291 /// Device class traits
3292 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3293 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3294 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3295 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3296 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN