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 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
59 //TODO: this can go away completely
60 const var_t variables[] = {
61 /* Server configuration */
62 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
64 /* Host configuration */
65 {"SubMesh", VAR_HOST | VAR_SAFE},
66 {"CanonicalAddress", VAR_HOST},
67 {"Address", VAR_HOST | VAR_MULTIPLE},
68 {"ECDSAPublicKey", VAR_HOST},
73 static bool fcopy(FILE *out, const char *filename) {
74 FILE *in = fopen(filename, "r");
77 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
84 while((len = fread(buf, 1, sizeof(buf), in))) {
85 fwrite(buf, len, 1, out);
92 static int rstrip(char *value) {
93 int len = strlen(value);
95 while(len && strchr("\t\r\n ", value[len - 1])) {
102 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
105 if(!filename || (*hostname && *port)) {
109 FILE *f = fopen(filename, "r");
115 while(fgets(line, sizeof(line), f)) {
121 p += strcspn(p, "\t =");
127 q = p + strspn(p, "\t ");
130 q += 1 + strspn(q + 1, "\t ");
133 // q is now pointing to the hostname
135 p = q + strcspn(q, "\t ");
141 p += strspn(p, "\t ");
142 p[strcspn(p, "\t ")] = 0;
143 // p is now pointing to the port, if present
145 if(!*port && !strcasecmp(line, "Port")) {
147 } else if(!strcasecmp(line, "CanonicalAddress")) {
148 *hostname = xstrdup(q);
156 if(*hostname && *port) {
164 static bool is_valid_hostname(const char *hostname) {
169 for(const char *p = hostname; *p; p++) {
170 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
178 static bool is_valid_port(const char *port) {
185 unsigned long int result = strtoul(port, &end, 10);
186 return result && result < 65536 && !*end;
189 for(const char *p = port; *p; p++) {
190 if(!(isalnum(*p) || *p == '-')) {
198 static void set_timeout(int sock, int timeout) {
203 tv.tv_sec = timeout / 1000;
204 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
206 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
207 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
210 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;
224 params->fd = socket(params->domain, params->type, params->protocol);
230 static int socket_in_netns(int domain, int type, int protocol, int netns) {
232 return socket(domain, type, protocol);
235 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
239 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
240 pthread_join(thr, NULL);
246 // Find out what local address a socket would use if we connect to the given address.
247 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
248 // of both endpoints, but this will actually not send any UDP packet.
249 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
250 struct addrinfo *rai = NULL;
251 const struct addrinfo hint = {
252 .ai_family = AF_UNSPEC,
253 .ai_socktype = SOCK_DGRAM,
254 .ai_protocol = IPPROTO_UDP,
257 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
261 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
268 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
276 struct sockaddr_storage sn;
277 socklen_t sl = sizeof(sn);
279 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
286 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
293 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
294 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
297 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
298 char *hostname = NULL;
300 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
301 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
302 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
305 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
306 if(family != AF_UNSPEC && aip->ai_family != family) {
310 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
313 set_timeout(s, 5000);
315 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
322 send(s, request, sizeof(request) - 1, 0);
323 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
328 if(line[len - 1] == '\n') {
332 char *p = strrchr(line, '\n');
335 hostname = xstrdup(p + 1);
351 // Check that the hostname is reasonable
352 if(hostname && !is_valid_hostname(hostname)) {
358 meshlink_errno = MESHLINK_ERESOLV;
364 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
367 // Determine address of the local interface used for outgoing connections.
368 char localaddr[NI_MAXHOST];
369 bool success = false;
371 if(family == AF_INET) {
372 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
373 } else if(family == AF_INET6) {
374 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
378 meshlink_errno = MESHLINK_ENETWORK;
382 return xstrdup(localaddr);
385 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
386 for(int i = 0; i < n; i++) {
391 // Ignore duplicate hostnames
394 for(int j = 0; j < i; j++) {
399 if(strcmp(host[i], host[j])) {
403 if(strcmp(port[i], port[j])) {
421 // This gets the hostname part for use in invitation URLs
422 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
423 char *hostname[4] = {NULL};
424 char *port[4] = {NULL};
425 char *hostport = NULL;
427 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
428 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
431 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
432 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
435 // Add local addresses if requested
436 if(flags & MESHLINK_INVITE_LOCAL) {
437 if(flags & MESHLINK_INVITE_IPV4) {
438 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
441 if(flags & MESHLINK_INVITE_IPV6) {
442 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
446 // Add public/canonical addresses if requested
447 if(flags & MESHLINK_INVITE_PUBLIC) {
448 // Try the CanonicalAddress first
449 char filename[PATH_MAX] = "";
450 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
451 scan_for_canonical_address(filename, &hostname[2], &port[2]);
454 if(flags & MESHLINK_INVITE_IPV4) {
455 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
458 if(flags & MESHLINK_INVITE_IPV6) {
459 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
464 for(int i = 0; i < 4; i++) {
465 // Ensure we always have a port number
466 if(hostname[i] && !port[i]) {
467 port[i] = xstrdup(mesh->myport);
471 remove_duplicate_hostnames(hostname, port, 4);
473 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
474 for(int i = 0; i < 4; i++) {
479 // Convert what we have to a sockaddr
480 struct addrinfo *ai_in, *ai_out;
481 struct addrinfo hint = {
482 .ai_family = AF_UNSPEC,
483 .ai_flags = AI_NUMERICSERV,
484 .ai_socktype = SOCK_STREAM,
486 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
492 // Convert it to a hostname
493 char resolved_host[NI_MAXHOST];
494 char resolved_port[NI_MAXSERV];
495 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
502 // Convert the hostname back to a sockaddr
503 hint.ai_family = ai_in->ai_family;
504 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
511 // Check if it's still the same sockaddr
512 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
514 freeaddrinfo(ai_out);
518 // Yes: replace the hostname with the resolved one
520 hostname[i] = xstrdup(resolved_host);
523 freeaddrinfo(ai_out);
527 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
528 remove_duplicate_hostnames(hostname, port, 4);
530 // Concatenate all unique address to the hostport string
531 for(int i = 0; i < 4; i++) {
536 // Ensure we have the same addresses in our own host config file.
538 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
539 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
542 // Append the address to the hostport string
544 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
546 hostport = newhostport;
555 static char *get_line(const char **data) {
556 if(!data || !*data) {
565 static char line[1024];
566 const char *end = strchr(*data, '\n');
567 size_t len = end ? (size_t)(end - *data) : strlen(*data);
569 if(len >= sizeof(line)) {
570 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
574 if(len && !isprint(**data)) {
578 memcpy(line, *data, len);
590 static char *get_value(const char *data, const char *var) {
591 char *line = get_line(&data);
597 char *sep = line + strcspn(line, " \t=");
598 char *val = sep + strspn(sep, " \t");
601 val += 1 + strspn(val + 1, " \t");
606 if(strcasecmp(line, var)) {
613 static bool try_bind(int port) {
614 struct addrinfo *ai = NULL;
615 struct addrinfo hint = {
616 .ai_flags = AI_PASSIVE,
617 .ai_family = AF_UNSPEC,
618 .ai_socktype = SOCK_STREAM,
619 .ai_protocol = IPPROTO_TCP,
623 snprintf(portstr, sizeof(portstr), "%d", port);
625 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
630 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
637 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
652 int check_port(meshlink_handle_t *mesh) {
653 for(int i = 0; i < 1000; i++) {
654 int port = 0x1000 + (rand() & 0x7fff);
657 char filename[PATH_MAX];
658 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
659 FILE *f = fopen(filename, "a");
662 meshlink_errno = MESHLINK_ESTORAGE;
663 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
667 fprintf(f, "Port = %d\n", port);
673 meshlink_errno = MESHLINK_ENETWORK;
674 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
678 static void deltree(const char *dirname) {
679 DIR *d = opendir(dirname);
684 while((ent = readdir(d))) {
685 if(ent->d_name[0] == '.') {
689 char filename[PATH_MAX];
690 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
692 if(unlink(filename)) {
703 static bool finalize_join(meshlink_handle_t *mesh) {
704 char *name = xstrdup(get_value(mesh->data, "Name"));
707 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
711 if(!check_id(name)) {
712 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
716 char filename[PATH_MAX];
717 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
719 FILE *f = fopen(filename, "w");
722 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
726 fprintf(f, "Name = %s\n", name);
728 // Wipe all old host config files and invitations
729 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
732 if(mkdir(filename, 0777) && errno != EEXIST) {
733 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
737 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
740 // Create a new host config file for ourself
741 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
742 FILE *fh = fopen(filename, "w");
745 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
750 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
751 // Other chunks go unfiltered to their respective host config files
752 const char *p = mesh->data;
755 while((l = get_line(&p))) {
761 // Split line into variable and value
762 int len = strcspn(l, "\t =");
764 value += strspn(value, "\t ");
768 value += strspn(value, "\t ");
774 if(!strcasecmp(l, "Name"))
775 if(strcmp(value, name)) {
779 } else if(!strcasecmp(l, "NetName")) {
783 // Check the list of known variables
787 for(i = 0; variables[i].name; i++) {
788 if(strcasecmp(l, variables[i].name)) {
796 // Ignore unknown and unsafe variables
798 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
800 } else if(!(variables[i].type & VAR_SAFE)) {
801 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
805 // Copy the safe variable to the right config file
806 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
811 while(l && !strcasecmp(l, "Name")) {
812 if(!check_id(value)) {
813 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
817 if(!strcmp(value, name)) {
818 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
822 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
823 f = fopen(filename, "w");
826 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
830 while((l = get_line(&p))) {
831 if(!strcmp(l, "#---------------------------------------------------------------#")) {
835 int len = strcspn(l, "\t =");
837 if(len == 4 && !strncasecmp(l, "Name", 4)) {
839 value += strspn(value, "\t ");
843 value += strspn(value, "\t ");
857 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
864 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
865 fprintf(fh, "Port = %s\n", mesh->myport);
869 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
873 free(mesh->self->name);
874 free(mesh->self->connection->name);
875 mesh->name = xstrdup(name);
876 mesh->self->name = xstrdup(name);
877 mesh->self->connection->name = name;
879 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
881 load_all_nodes(mesh);
886 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
888 meshlink_handle_t *mesh = handle;
889 const char *ptr = data;
892 int result = send(mesh->sock, ptr, len, 0);
894 if(result == -1 && errno == EINTR) {
896 } else if(result <= 0) {
907 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
908 meshlink_handle_t *mesh = handle;
911 case SPTPS_HANDSHAKE:
912 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
915 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
916 memcpy(mesh->data + mesh->thedatalen, msg, len);
917 mesh->thedatalen += len;
918 mesh->data[mesh->thedatalen] = 0;
922 mesh->thedatalen = 0;
923 return finalize_join(mesh);
926 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
927 shutdown(mesh->sock, SHUT_RDWR);
928 mesh->success = true;
938 static bool recvline(meshlink_handle_t *mesh, size_t len) {
939 char *newline = NULL;
945 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
946 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
948 if(result == -1 && errno == EINTR) {
950 } else if(result <= 0) {
954 mesh->blen += result;
957 if((size_t)(newline - mesh->buffer) >= len) {
961 len = newline - mesh->buffer;
963 memcpy(mesh->line, mesh->buffer, len);
965 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
966 mesh->blen -= len + 1;
970 static bool sendline(int fd, char *format, ...) {
971 static char buffer[4096];
976 va_start(ap, format);
977 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
980 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
988 int result = send(fd, p, blen, MSG_NOSIGNAL);
990 if(result == -1 && errno == EINTR) {
992 } else if(result <= 0) {
1003 static const char *errstr[] = {
1004 [MESHLINK_OK] = "No error",
1005 [MESHLINK_EINVAL] = "Invalid argument",
1006 [MESHLINK_ENOMEM] = "Out of memory",
1007 [MESHLINK_ENOENT] = "No such node",
1008 [MESHLINK_EEXIST] = "Node already exists",
1009 [MESHLINK_EINTERNAL] = "Internal error",
1010 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1011 [MESHLINK_ESTORAGE] = "Storage error",
1012 [MESHLINK_ENETWORK] = "Network error",
1013 [MESHLINK_EPEER] = "Error communicating with peer",
1014 [MESHLINK_ENOTSUP] = "Operation not supported",
1015 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1018 const char *meshlink_strerror(meshlink_errno_t err) {
1019 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1020 return "Invalid error code";
1026 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1029 char pubname[PATH_MAX], privname[PATH_MAX];
1031 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1033 if(!(key = ecdsa_generate())) {
1034 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1035 meshlink_errno = MESHLINK_EINTERNAL;
1038 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1041 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1042 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1043 meshlink_errno = MESHLINK_ESTORAGE;
1047 f = fopen(privname, "wb");
1050 meshlink_errno = MESHLINK_ESTORAGE;
1055 fchmod(fileno(f), 0600);
1058 if(!ecdsa_write_pem_private_key(key, f)) {
1059 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1062 meshlink_errno = MESHLINK_EINTERNAL;
1068 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1069 f = fopen(pubname, "a");
1072 meshlink_errno = MESHLINK_ESTORAGE;
1076 char *pubkey = ecdsa_get_base64_public_key(key);
1077 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1086 static struct timeval idle(event_loop_t *loop, void *data) {
1088 meshlink_handle_t *mesh = data;
1089 struct timeval t, tmin = {3600, 0};
1091 for splay_each(node_t, n, mesh->nodes) {
1096 t = utcp_timeout(n->utcp);
1098 if(timercmp(&t, &tmin, <)) {
1106 // Get our local address(es) by simulating connecting to an Internet host.
1107 static void add_local_addresses(meshlink_handle_t *mesh) {
1108 char host[NI_MAXHOST];
1109 char entry[MAX_STRING_SIZE];
1113 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1114 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1115 append_config_file(mesh, mesh->name, "Address", entry);
1120 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1121 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1122 append_config_file(mesh, mesh->name, "Address", entry);
1126 static bool meshlink_setup(meshlink_handle_t *mesh) {
1127 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1128 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1129 meshlink_errno = MESHLINK_ESTORAGE;
1133 char filename[PATH_MAX];
1134 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1136 if(mkdir(filename, 0777) && errno != EEXIST) {
1137 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1138 meshlink_errno = MESHLINK_ESTORAGE;
1142 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1144 if(!access(filename, F_OK)) {
1145 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1146 meshlink_errno = MESHLINK_EEXIST;
1150 FILE *f = fopen(filename, "w");
1153 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1154 meshlink_errno = MESHLINK_ESTORAGE;
1158 fprintf(f, "Name = %s\n", mesh->name);
1161 if(!ecdsa_keygen(mesh)) {
1162 meshlink_errno = MESHLINK_EINTERNAL;
1167 if(check_port(mesh) == 0) {
1168 meshlink_errno = MESHLINK_ENETWORK;
1176 static void *setup_network_in_netns_thread(void *arg) {
1177 meshlink_handle_t *mesh = arg;
1179 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1183 bool success = setup_network(mesh);
1184 add_local_addresses(mesh);
1185 return success ? arg : NULL;
1188 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1189 if(!confbase || !*confbase) {
1190 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1191 meshlink_errno = MESHLINK_EINVAL;
1195 if(!appname || !*appname) {
1196 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1197 meshlink_errno = MESHLINK_EINVAL;
1201 if(strchr(appname, ' ')) {
1202 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1203 meshlink_errno = MESHLINK_EINVAL;
1207 if(!name || !*name) {
1208 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1210 } else { //check name only if there is a name != NULL
1211 if(!check_id(name)) {
1212 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1213 meshlink_errno = MESHLINK_EINVAL;
1218 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1219 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1220 meshlink_errno = MESHLINK_EINVAL;
1224 meshlink_open_params_t *params = xzalloc(sizeof * params);
1226 params->confbase = xstrdup(confbase);
1227 params->name = xstrdup(name);
1228 params->appname = xstrdup(appname);
1229 params->devclass = devclass;
1235 void meshlink_open_params_free(meshlink_open_params_t *params) {
1237 meshlink_errno = MESHLINK_EINVAL;
1241 free(params->confbase);
1243 free(params->appname);
1248 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1249 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1250 meshlink_open_params_t params = {NULL};
1252 params.confbase = (char *)confbase;
1253 params.name = (char *)name;
1254 params.appname = (char *)appname;
1255 params.devclass = devclass;
1258 return meshlink_open_ex(¶ms);
1260 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1261 // Validate arguments provided by the application
1262 bool usingname = false;
1264 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1266 if(!params->confbase || !*params->confbase) {
1267 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1268 meshlink_errno = MESHLINK_EINVAL;
1272 if(!params->appname || !*params->appname) {
1273 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1274 meshlink_errno = MESHLINK_EINVAL;
1278 if(strchr(params->appname, ' ')) {
1279 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1280 meshlink_errno = MESHLINK_EINVAL;
1284 if(!params->name || !*params->name) {
1285 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1287 } else { //check name only if there is a name != NULL
1289 if(!check_id(params->name)) {
1290 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1291 meshlink_errno = MESHLINK_EINVAL;
1298 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1299 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1300 meshlink_errno = MESHLINK_EINVAL;
1304 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1305 mesh->confbase = xstrdup(params->confbase);
1306 mesh->appname = xstrdup(params->appname);
1307 mesh->devclass = params->devclass;
1308 mesh->discovery = true;
1309 mesh->invitation_timeout = 604800; // 1 week
1310 mesh->netns = params->netns;
1311 mesh->submeshes = NULL;
1314 mesh->name = xstrdup(params->name);
1318 pthread_mutexattr_t attr;
1319 pthread_mutexattr_init(&attr);
1320 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1321 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1323 mesh->threadstarted = false;
1324 event_loop_init(&mesh->loop);
1325 mesh->loop.data = mesh;
1327 meshlink_queue_init(&mesh->outpacketqueue);
1329 // Check whether meshlink.conf already exists
1331 char filename[PATH_MAX];
1332 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1334 if(access(filename, R_OK)) {
1335 if(errno == ENOENT) {
1336 // If not, create it
1337 if(!meshlink_setup(mesh)) {
1338 // meshlink_errno is set by meshlink_setup()
1342 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1343 meshlink_close(mesh);
1344 meshlink_errno = MESHLINK_ESTORAGE;
1349 // Open the configuration file and lock it
1351 mesh->conffile = fopen(filename, "r");
1353 if(!mesh->conffile) {
1354 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1355 meshlink_close(mesh);
1356 meshlink_errno = MESHLINK_ESTORAGE;
1361 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1365 // TODO: use _locking()?
1368 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1369 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1370 meshlink_close(mesh);
1371 meshlink_errno = MESHLINK_EBUSY;
1377 // Read the configuration
1379 init_configuration(&mesh->config);
1381 if(!read_server_config(mesh)) {
1382 meshlink_close(mesh);
1383 meshlink_errno = MESHLINK_ESTORAGE;
1388 struct WSAData wsa_state;
1390 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1394 // Setup up everything
1395 // TODO: we should not open listening sockets yet
1397 bool success = false;
1399 if(mesh->netns != -1) {
1402 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1403 void *retval = NULL;
1404 success = pthread_join(thr, &retval) == 0 && retval;
1407 success = setup_network(mesh);
1408 add_local_addresses(mesh);
1412 meshlink_close(mesh);
1413 meshlink_errno = MESHLINK_ENETWORK;
1417 idle_set(&mesh->loop, idle, mesh);
1419 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1423 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1424 meshlink_submesh_t *s = NULL;
1427 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1428 meshlink_errno = MESHLINK_EINVAL;
1432 if(!submesh || !*submesh) {
1433 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1434 meshlink_errno = MESHLINK_EINVAL;
1439 pthread_mutex_lock(&(mesh->mesh_mutex));
1441 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1443 pthread_mutex_unlock(&(mesh->mesh_mutex));
1448 static void *meshlink_main_loop(void *arg) {
1449 meshlink_handle_t *mesh = arg;
1451 if(mesh->netns != -1) {
1452 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1457 pthread_mutex_lock(&(mesh->mesh_mutex));
1459 try_outgoing_connections(mesh);
1461 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1463 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1465 pthread_mutex_unlock(&(mesh->mesh_mutex));
1469 bool meshlink_start(meshlink_handle_t *mesh) {
1471 meshlink_errno = MESHLINK_EINVAL;
1475 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1477 pthread_mutex_lock(&(mesh->mesh_mutex));
1479 if(mesh->threadstarted) {
1480 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1481 pthread_mutex_unlock(&(mesh->mesh_mutex));
1485 if(mesh->listen_socket[0].tcp.fd < 0) {
1486 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1487 meshlink_errno = MESHLINK_ENETWORK;
1491 mesh->thedatalen = 0;
1493 // TODO: open listening sockets first
1495 //Check that a valid name is set
1497 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1498 meshlink_errno = MESHLINK_EINVAL;
1499 pthread_mutex_unlock(&(mesh->mesh_mutex));
1503 // Start the main thread
1505 event_loop_start(&mesh->loop);
1507 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1508 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1509 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1510 meshlink_errno = MESHLINK_EINTERNAL;
1511 event_loop_stop(&mesh->loop);
1512 pthread_mutex_unlock(&(mesh->mesh_mutex));
1516 mesh->threadstarted = true;
1520 if(mesh->discovery) {
1521 discovery_start(mesh);
1526 pthread_mutex_unlock(&(mesh->mesh_mutex));
1530 void meshlink_stop(meshlink_handle_t *mesh) {
1532 meshlink_errno = MESHLINK_EINVAL;
1536 pthread_mutex_lock(&(mesh->mesh_mutex));
1537 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1542 if(mesh->discovery) {
1543 discovery_stop(mesh);
1548 // Shut down the main thread
1549 event_loop_stop(&mesh->loop);
1551 // Send ourselves a UDP packet to kick the event loop
1552 for(int i = 0; i < mesh->listen_sockets; i++) {
1554 socklen_t salen = sizeof(sa.sa);
1556 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1557 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1561 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1562 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1566 if(mesh->threadstarted) {
1567 // Wait for the main thread to finish
1568 pthread_mutex_unlock(&(mesh->mesh_mutex));
1569 pthread_join(mesh->thread, NULL);
1570 pthread_mutex_lock(&(mesh->mesh_mutex));
1572 mesh->threadstarted = false;
1575 // Close all metaconnections
1576 if(mesh->connections) {
1577 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1579 connection_t *c = node->data;
1581 terminate_connection(mesh, c, false);
1585 if(mesh->outgoings) {
1586 list_delete_list(mesh->outgoings);
1587 mesh->outgoings = NULL;
1590 pthread_mutex_unlock(&(mesh->mesh_mutex));
1593 void meshlink_close(meshlink_handle_t *mesh) {
1594 if(!mesh || !mesh->confbase) {
1595 meshlink_errno = MESHLINK_EINVAL;
1599 // stop can be called even if mesh has not been started
1600 meshlink_stop(mesh);
1602 // lock is not released after this
1603 pthread_mutex_lock(&(mesh->mesh_mutex));
1605 // Close and free all resources used.
1607 close_network_connections(mesh);
1609 logger(mesh, MESHLINK_INFO, "Terminating");
1611 exit_configuration(&mesh->config);
1612 event_loop_exit(&mesh->loop);
1616 if(mesh->confbase) {
1622 ecdsa_free(mesh->invitation_key);
1624 if(mesh->netns != -1) {
1629 free(mesh->appname);
1630 free(mesh->confbase);
1631 pthread_mutex_destroy(&(mesh->mesh_mutex));
1633 if(mesh->conffile) {
1634 fclose(mesh->conffile);
1637 memset(mesh, 0, sizeof(*mesh));
1642 bool meshlink_destroy(const char *confbase) {
1644 meshlink_errno = MESHLINK_EINVAL;
1648 char filename[PATH_MAX];
1649 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1651 if(unlink(filename)) {
1652 if(errno == ENOENT) {
1653 meshlink_errno = MESHLINK_ENOENT;
1656 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1657 meshlink_errno = MESHLINK_ESTORAGE;
1667 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1669 meshlink_errno = MESHLINK_EINVAL;
1673 pthread_mutex_lock(&(mesh->mesh_mutex));
1674 mesh->receive_cb = cb;
1675 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1680 meshlink_errno = MESHLINK_EINVAL;
1684 pthread_mutex_lock(&(mesh->mesh_mutex));
1685 mesh->node_status_cb = cb;
1686 pthread_mutex_unlock(&(mesh->mesh_mutex));
1689 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1691 meshlink_errno = MESHLINK_EINVAL;
1695 pthread_mutex_lock(&(mesh->mesh_mutex));
1696 mesh->node_duplicate_cb = cb;
1697 pthread_mutex_unlock(&(mesh->mesh_mutex));
1700 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1702 pthread_mutex_lock(&(mesh->mesh_mutex));
1704 mesh->log_level = cb ? level : 0;
1705 pthread_mutex_unlock(&(mesh->mesh_mutex));
1708 global_log_level = cb ? level : 0;
1712 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1713 meshlink_packethdr_t *hdr;
1715 // Validate arguments
1716 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1717 meshlink_errno = MESHLINK_EINVAL;
1726 meshlink_errno = MESHLINK_EINVAL;
1730 node_t *n = (node_t *)destination;
1732 if(n->status.blacklisted) {
1733 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1737 // Prepare the packet
1738 vpn_packet_t *packet = malloc(sizeof(*packet));
1741 meshlink_errno = MESHLINK_ENOMEM;
1745 packet->probe = false;
1746 packet->tcp = false;
1747 packet->len = len + sizeof(*hdr);
1749 hdr = (meshlink_packethdr_t *)packet->data;
1750 memset(hdr, 0, sizeof(*hdr));
1751 // leave the last byte as 0 to make sure strings are always
1752 // null-terminated if they are longer than the buffer
1753 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1754 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1756 memcpy(packet->data + sizeof(*hdr), data, len);
1759 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1761 meshlink_errno = MESHLINK_ENOMEM;
1765 // Notify event loop
1766 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1771 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1773 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1779 mesh->self->in_packets++;
1780 mesh->self->in_bytes += packet->len;
1781 route(mesh, mesh->self, packet);
1784 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1785 if(!mesh || !destination) {
1786 meshlink_errno = MESHLINK_EINVAL;
1790 pthread_mutex_lock(&(mesh->mesh_mutex));
1792 node_t *n = (node_t *)destination;
1794 if(!n->status.reachable) {
1795 pthread_mutex_unlock(&(mesh->mesh_mutex));
1798 } else if(n->mtuprobes > 30 && n->minmtu) {
1799 pthread_mutex_unlock(&(mesh->mesh_mutex));
1802 pthread_mutex_unlock(&(mesh->mesh_mutex));
1807 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1808 if(!mesh || !node) {
1809 meshlink_errno = MESHLINK_EINVAL;
1813 pthread_mutex_lock(&(mesh->mesh_mutex));
1815 node_t *n = (node_t *)node;
1817 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1818 meshlink_errno = MESHLINK_EINTERNAL;
1819 pthread_mutex_unlock(&(mesh->mesh_mutex));
1823 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1826 meshlink_errno = MESHLINK_EINTERNAL;
1829 pthread_mutex_unlock(&(mesh->mesh_mutex));
1833 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1835 meshlink_errno = MESHLINK_EINVAL;
1839 return (meshlink_node_t *)mesh->self;
1842 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1843 if(!mesh || !name) {
1844 meshlink_errno = MESHLINK_EINVAL;
1848 meshlink_node_t *node = NULL;
1850 pthread_mutex_lock(&(mesh->mesh_mutex));
1851 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1852 pthread_mutex_unlock(&(mesh->mesh_mutex));
1856 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1857 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1858 meshlink_errno = MESHLINK_EINVAL;
1862 meshlink_node_t **result;
1865 pthread_mutex_lock(&(mesh->mesh_mutex));
1867 *nmemb = mesh->nodes->count;
1868 result = realloc(nodes, *nmemb * sizeof(*nodes));
1871 meshlink_node_t **p = result;
1873 for splay_each(node_t, n, mesh->nodes) {
1874 *p++ = (meshlink_node_t *)n;
1879 meshlink_errno = MESHLINK_ENOMEM;
1882 pthread_mutex_unlock(&(mesh->mesh_mutex));
1887 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) {
1888 meshlink_node_t **result;
1890 pthread_mutex_lock(&(mesh->mesh_mutex));
1894 for splay_each(node_t, n, mesh->nodes) {
1895 if(true == search_node(n, condition)) {
1896 *nmemb = *nmemb + 1;
1902 pthread_mutex_unlock(&(mesh->mesh_mutex));
1906 result = realloc(nodes, *nmemb * sizeof(*nodes));
1909 meshlink_node_t **p = result;
1911 for splay_each(node_t, n, mesh->nodes) {
1912 if(true == search_node(n, condition)) {
1913 *p++ = (meshlink_node_t *)n;
1919 meshlink_errno = MESHLINK_ENOMEM;
1922 pthread_mutex_unlock(&(mesh->mesh_mutex));
1927 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1928 dev_class_t *devclass = (dev_class_t *)condition;
1930 if(*devclass == node->devclass) {
1937 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1938 if(condition == node->submesh) {
1945 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) {
1946 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1947 meshlink_errno = MESHLINK_EINVAL;
1951 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1954 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1955 if(!mesh || !submesh || !nmemb) {
1956 meshlink_errno = MESHLINK_EINVAL;
1960 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1963 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1964 if(!mesh || !node) {
1965 meshlink_errno = MESHLINK_EINVAL;
1969 dev_class_t devclass;
1971 pthread_mutex_lock(&(mesh->mesh_mutex));
1973 devclass = ((node_t *)node)->devclass;
1975 pthread_mutex_unlock(&(mesh->mesh_mutex));
1980 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1981 if(!mesh || !node) {
1982 meshlink_errno = MESHLINK_EINVAL;
1986 node_t *n = (node_t *)node;
1988 meshlink_submesh_t *s;
1990 s = (meshlink_submesh_t *)n->submesh;
1995 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1996 if(!mesh || !data || !len || !signature || !siglen) {
1997 meshlink_errno = MESHLINK_EINVAL;
2001 if(*siglen < MESHLINK_SIGLEN) {
2002 meshlink_errno = MESHLINK_EINVAL;
2006 pthread_mutex_lock(&(mesh->mesh_mutex));
2008 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
2009 meshlink_errno = MESHLINK_EINTERNAL;
2010 pthread_mutex_unlock(&(mesh->mesh_mutex));
2014 *siglen = MESHLINK_SIGLEN;
2015 pthread_mutex_unlock(&(mesh->mesh_mutex));
2019 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2020 if(!mesh || !data || !len || !signature) {
2021 meshlink_errno = MESHLINK_EINVAL;
2025 if(siglen != MESHLINK_SIGLEN) {
2026 meshlink_errno = MESHLINK_EINVAL;
2030 pthread_mutex_lock(&(mesh->mesh_mutex));
2034 struct node_t *n = (struct node_t *)source;
2035 node_read_ecdsa_public_key(mesh, n);
2038 meshlink_errno = MESHLINK_EINTERNAL;
2041 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2044 pthread_mutex_unlock(&(mesh->mesh_mutex));
2048 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2049 char filename[PATH_MAX];
2051 pthread_mutex_lock(&(mesh->mesh_mutex));
2053 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2055 if(mkdir(filename, 0700) && errno != EEXIST) {
2056 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2057 meshlink_errno = MESHLINK_ESTORAGE;
2058 pthread_mutex_unlock(&(mesh->mesh_mutex));
2062 // Count the number of valid invitations, clean up old ones
2063 DIR *dir = opendir(filename);
2066 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2067 meshlink_errno = MESHLINK_ESTORAGE;
2068 pthread_mutex_unlock(&(mesh->mesh_mutex));
2075 time_t deadline = time(NULL) - 604800; // 1 week in the past
2077 while((ent = readdir(dir))) {
2078 if(strlen(ent->d_name) != 24) {
2082 char invname[PATH_MAX];
2085 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2086 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2090 if(!stat(invname, &st)) {
2091 if(mesh->invitation_key && deadline < st.st_mtime) {
2097 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2103 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2105 meshlink_errno = MESHLINK_ESTORAGE;
2106 pthread_mutex_unlock(&(mesh->mesh_mutex));
2112 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2114 // Remove the key if there are no outstanding invitations.
2118 if(mesh->invitation_key) {
2119 ecdsa_free(mesh->invitation_key);
2120 mesh->invitation_key = NULL;
2124 if(mesh->invitation_key) {
2125 pthread_mutex_unlock(&(mesh->mesh_mutex));
2129 // Create a new key if necessary.
2130 FILE *f = fopen(filename, "rb");
2133 if(errno != ENOENT) {
2134 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2135 meshlink_errno = MESHLINK_ESTORAGE;
2136 pthread_mutex_unlock(&(mesh->mesh_mutex));
2140 mesh->invitation_key = ecdsa_generate();
2142 if(!mesh->invitation_key) {
2143 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2144 meshlink_errno = MESHLINK_EINTERNAL;
2145 pthread_mutex_unlock(&(mesh->mesh_mutex));
2149 f = fopen(filename, "wb");
2152 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2153 meshlink_errno = MESHLINK_ESTORAGE;
2154 pthread_mutex_unlock(&(mesh->mesh_mutex));
2158 chmod(filename, 0600);
2159 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2162 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2165 if(!mesh->invitation_key) {
2166 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2167 meshlink_errno = MESHLINK_ESTORAGE;
2171 pthread_mutex_unlock(&(mesh->mesh_mutex));
2172 return mesh->invitation_key;
2175 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2176 if(!mesh || !node || !address) {
2177 meshlink_errno = MESHLINK_EINVAL;
2181 if(!is_valid_hostname(address)) {
2182 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2183 meshlink_errno = MESHLINK_EINVAL;
2187 if(port && !is_valid_port(port)) {
2188 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2189 meshlink_errno = MESHLINK_EINVAL;
2193 char *canonical_address;
2196 xasprintf(&canonical_address, "%s %s", address, port);
2198 canonical_address = xstrdup(address);
2201 pthread_mutex_lock(&(mesh->mesh_mutex));
2202 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2203 pthread_mutex_unlock(&(mesh->mesh_mutex));
2205 free(canonical_address);
2209 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2210 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2213 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2215 meshlink_errno = MESHLINK_EINVAL;
2219 char *address = meshlink_get_external_address(mesh);
2227 pthread_mutex_lock(&(mesh->mesh_mutex));
2228 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2229 pthread_mutex_unlock(&(mesh->mesh_mutex));
2235 int meshlink_get_port(meshlink_handle_t *mesh) {
2237 meshlink_errno = MESHLINK_EINVAL;
2242 meshlink_errno = MESHLINK_EINTERNAL;
2246 return atoi(mesh->myport);
2249 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2250 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2251 meshlink_errno = MESHLINK_EINVAL;
2255 if(mesh->myport && port == atoi(mesh->myport)) {
2259 if(!try_bind(port)) {
2260 meshlink_errno = MESHLINK_ENETWORK;
2266 pthread_mutex_lock(&(mesh->mesh_mutex));
2268 if(mesh->threadstarted) {
2269 meshlink_errno = MESHLINK_EINVAL;
2273 close_network_connections(mesh);
2274 exit_configuration(&mesh->config);
2277 snprintf(portstr, sizeof(portstr), "%d", port);
2278 portstr[sizeof(portstr) - 1] = 0;
2280 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2282 init_configuration(&mesh->config);
2284 if(!read_server_config(mesh)) {
2285 meshlink_errno = MESHLINK_ESTORAGE;
2286 } else if(!setup_network(mesh)) {
2287 meshlink_errno = MESHLINK_ENETWORK;
2293 pthread_mutex_unlock(&(mesh->mesh_mutex));
2298 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2299 mesh->invitation_timeout = timeout;
2302 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2303 meshlink_submesh_t *s = NULL;
2306 meshlink_errno = MESHLINK_EINVAL;
2311 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2314 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2315 meshlink_errno = MESHLINK_EINVAL;
2319 s = (meshlink_submesh_t *)mesh->self->submesh;
2322 pthread_mutex_lock(&(mesh->mesh_mutex));
2324 // Check validity of the new node's name
2325 if(!check_id(name)) {
2326 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2327 meshlink_errno = MESHLINK_EINVAL;
2328 pthread_mutex_unlock(&(mesh->mesh_mutex));
2332 // Ensure no host configuration file with that name exists
2333 char filename[PATH_MAX];
2334 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2336 if(!access(filename, F_OK)) {
2337 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2338 meshlink_errno = MESHLINK_EEXIST;
2339 pthread_mutex_unlock(&(mesh->mesh_mutex));
2343 // Ensure no other nodes know about this name
2344 if(meshlink_get_node(mesh, name)) {
2345 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2346 meshlink_errno = MESHLINK_EEXIST;
2347 pthread_mutex_unlock(&(mesh->mesh_mutex));
2351 // Get the local address
2352 char *address = get_my_hostname(mesh, flags);
2355 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2356 meshlink_errno = MESHLINK_ERESOLV;
2357 pthread_mutex_unlock(&(mesh->mesh_mutex));
2361 if(!refresh_invitation_key(mesh)) {
2362 meshlink_errno = MESHLINK_EINTERNAL;
2363 pthread_mutex_unlock(&(mesh->mesh_mutex));
2369 // Create a hash of the key.
2370 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2371 sha512(fingerprint, strlen(fingerprint), hash);
2372 b64encode_urlsafe(hash, hash, 18);
2374 // Create a random cookie for this invitation.
2376 randomize(cookie, 18);
2378 // Create a filename that doesn't reveal the cookie itself
2379 char buf[18 + strlen(fingerprint)];
2380 char cookiehash[64];
2381 memcpy(buf, cookie, 18);
2382 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2383 sha512(buf, sizeof(buf), cookiehash);
2384 b64encode_urlsafe(cookiehash, cookiehash, 18);
2386 b64encode_urlsafe(cookie, cookie, 18);
2390 // Create a file containing the details of the invitation.
2391 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2392 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2395 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2396 meshlink_errno = MESHLINK_ESTORAGE;
2397 pthread_mutex_unlock(&(mesh->mesh_mutex));
2401 FILE *f = fdopen(ifd, "w");
2407 // Fill in the details.
2408 fprintf(f, "Name = %s\n", name);
2411 fprintf(f, "SubMesh = %s\n", s->name);
2414 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2416 // Copy Broadcast and Mode
2417 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2418 FILE *tc = fopen(filename, "r");
2423 while(fgets(buf, sizeof(buf), tc)) {
2424 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2425 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2428 // Make sure there is a newline character.
2429 if(!strchr(buf, '\n')) {
2437 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2438 meshlink_errno = MESHLINK_ESTORAGE;
2439 pthread_mutex_unlock(&(mesh->mesh_mutex));
2443 fprintf(f, "#---------------------------------------------------------------#\n");
2444 fprintf(f, "Name = %s\n", mesh->self->name);
2446 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2450 // Create an URL from the local address, key hash and cookie
2452 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2455 pthread_mutex_unlock(&(mesh->mesh_mutex));
2459 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2460 return meshlink_invite_ex(mesh, submesh, name, 0);
2463 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2464 if(!mesh || !invitation) {
2465 meshlink_errno = MESHLINK_EINVAL;
2469 pthread_mutex_lock(&(mesh->mesh_mutex));
2471 //Before doing meshlink_join make sure we are not connected to another mesh
2472 if(mesh->threadstarted) {
2473 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2474 meshlink_errno = MESHLINK_EINVAL;
2475 pthread_mutex_unlock(&(mesh->mesh_mutex));
2479 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2480 char copy[strlen(invitation) + 1];
2481 strcpy(copy, invitation);
2483 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2485 char *slash = strchr(copy, '/');
2493 if(strlen(slash) != 48) {
2497 char *address = copy;
2500 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2504 // Generate a throw-away key for the invitation.
2505 ecdsa_t *key = ecdsa_generate();
2508 meshlink_errno = MESHLINK_EINTERNAL;
2509 pthread_mutex_unlock(&(mesh->mesh_mutex));
2513 char *b64key = ecdsa_get_base64_public_key(key);
2517 while(address && *address) {
2518 // We allow commas in the address part to support multiple addresses in one invitation URL.
2519 comma = strchr(address, ',');
2525 // Split of the port
2526 port = strrchr(address, ':');
2534 // IPv6 address are enclosed in brackets, per RFC 3986
2535 if(*address == '[') {
2537 char *bracket = strchr(address, ']');
2550 // Connect to the meshlink daemon mentioned in the URL.
2551 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2554 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2555 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2557 if(mesh->sock == -1) {
2558 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2559 meshlink_errno = MESHLINK_ENETWORK;
2563 set_timeout(mesh->sock, 5000);
2565 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2566 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2567 meshlink_errno = MESHLINK_ENETWORK;
2568 closesocket(mesh->sock);
2576 meshlink_errno = MESHLINK_ERESOLV;
2579 if(mesh->sock != -1 || !comma) {
2586 if(mesh->sock == -1) {
2587 pthread_mutex_unlock(&mesh->mesh_mutex);
2591 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2593 // Tell him we have an invitation, and give him our throw-away key.
2597 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2598 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2599 closesocket(mesh->sock);
2600 meshlink_errno = MESHLINK_ENETWORK;
2601 pthread_mutex_unlock(&(mesh->mesh_mutex));
2607 char hisname[4096] = "";
2608 int code, hismajor, hisminor = 0;
2610 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) {
2611 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2612 closesocket(mesh->sock);
2613 meshlink_errno = MESHLINK_ENETWORK;
2614 pthread_mutex_unlock(&(mesh->mesh_mutex));
2618 // Check if the hash of the key he gave us matches the hash in the URL.
2619 char *fingerprint = mesh->line + 2;
2622 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2623 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2624 meshlink_errno = MESHLINK_EINTERNAL;
2625 pthread_mutex_unlock(&(mesh->mesh_mutex));
2629 if(memcmp(hishash, mesh->hash, 18)) {
2630 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2631 meshlink_errno = MESHLINK_EPEER;
2632 pthread_mutex_unlock(&(mesh->mesh_mutex));
2637 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2640 meshlink_errno = MESHLINK_EINTERNAL;
2641 pthread_mutex_unlock(&(mesh->mesh_mutex));
2645 // Start an SPTPS session
2646 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2647 meshlink_errno = MESHLINK_EINTERNAL;
2648 pthread_mutex_unlock(&(mesh->mesh_mutex));
2652 // Feed rest of input buffer to SPTPS
2653 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2654 meshlink_errno = MESHLINK_EPEER;
2655 pthread_mutex_unlock(&(mesh->mesh_mutex));
2661 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2663 if(errno == EINTR) {
2667 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2668 meshlink_errno = MESHLINK_ENETWORK;
2669 pthread_mutex_unlock(&(mesh->mesh_mutex));
2673 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2674 meshlink_errno = MESHLINK_EPEER;
2675 pthread_mutex_unlock(&(mesh->mesh_mutex));
2680 sptps_stop(&mesh->sptps);
2683 closesocket(mesh->sock);
2685 if(!mesh->success) {
2686 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2687 meshlink_errno = MESHLINK_EPEER;
2688 pthread_mutex_unlock(&(mesh->mesh_mutex));
2692 pthread_mutex_unlock(&(mesh->mesh_mutex));
2696 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2697 meshlink_errno = MESHLINK_EINVAL;
2698 pthread_mutex_unlock(&(mesh->mesh_mutex));
2702 char *meshlink_export(meshlink_handle_t *mesh) {
2704 meshlink_errno = MESHLINK_EINVAL;
2708 pthread_mutex_lock(&(mesh->mesh_mutex));
2710 char filename[PATH_MAX];
2711 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2712 FILE *f = fopen(filename, "r");
2715 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2716 meshlink_errno = MESHLINK_ESTORAGE;
2717 pthread_mutex_unlock(&(mesh->mesh_mutex));
2721 fseek(f, 0, SEEK_END);
2722 int fsize = ftell(f);
2725 size_t len = fsize + 9 + strlen(mesh->self->name);
2726 char *buf = xmalloc(len);
2727 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2729 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2730 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2733 meshlink_errno = MESHLINK_ESTORAGE;
2734 pthread_mutex_unlock(&(mesh->mesh_mutex));
2741 pthread_mutex_unlock(&(mesh->mesh_mutex));
2745 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2746 if(!mesh || !data) {
2747 meshlink_errno = MESHLINK_EINVAL;
2751 pthread_mutex_lock(&(mesh->mesh_mutex));
2753 if(strncmp(data, "Name = ", 7)) {
2754 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2755 meshlink_errno = MESHLINK_EPEER;
2756 pthread_mutex_unlock(&(mesh->mesh_mutex));
2760 char *end = strchr(data + 7, '\n');
2763 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2764 meshlink_errno = MESHLINK_EPEER;
2765 pthread_mutex_unlock(&(mesh->mesh_mutex));
2769 int len = end - (data + 7);
2771 memcpy(name, data + 7, len);
2774 if(!check_id(name)) {
2775 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2776 meshlink_errno = MESHLINK_EPEER;
2777 pthread_mutex_unlock(&(mesh->mesh_mutex));
2781 char filename[PATH_MAX];
2782 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2784 if(!access(filename, F_OK)) {
2785 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2786 meshlink_errno = MESHLINK_EEXIST;
2787 pthread_mutex_unlock(&(mesh->mesh_mutex));
2791 if(errno != ENOENT) {
2792 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2793 meshlink_errno = MESHLINK_ESTORAGE;
2794 pthread_mutex_unlock(&(mesh->mesh_mutex));
2798 FILE *f = fopen(filename, "w");
2801 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2802 meshlink_errno = MESHLINK_ESTORAGE;
2803 pthread_mutex_unlock(&(mesh->mesh_mutex));
2807 fwrite(end + 1, strlen(end + 1), 1, f);
2810 load_all_nodes(mesh);
2812 pthread_mutex_unlock(&(mesh->mesh_mutex));
2816 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2817 if(!mesh || !node) {
2818 meshlink_errno = MESHLINK_EINVAL;
2822 pthread_mutex_lock(&(mesh->mesh_mutex));
2827 if(n == mesh->self) {
2828 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2829 meshlink_errno = MESHLINK_EINVAL;
2830 pthread_mutex_unlock(&(mesh->mesh_mutex));
2834 if(n->status.blacklisted) {
2835 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2836 pthread_mutex_unlock(&(mesh->mesh_mutex));
2840 n->status.blacklisted = true;
2841 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2843 //Make blacklisting persistent in the config file
2844 append_config_file(mesh, n->name, "blacklisted", "yes");
2846 //Immediately terminate any connections we have with the blacklisted node
2847 for list_each(connection_t, c, mesh->connections) {
2849 terminate_connection(mesh, c, c->status.active);
2853 utcp_abort_all_connections(n->utcp);
2859 n->status.udp_confirmed = false;
2861 if(n->status.reachable) {
2862 update_node_status(mesh, n);
2865 pthread_mutex_unlock(&(mesh->mesh_mutex));
2868 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2869 if(!mesh || !node) {
2870 meshlink_errno = MESHLINK_EINVAL;
2874 pthread_mutex_lock(&(mesh->mesh_mutex));
2876 node_t *n = (node_t *)node;
2878 if(!n->status.blacklisted) {
2879 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2880 meshlink_errno = MESHLINK_EINVAL;
2881 pthread_mutex_unlock(&(mesh->mesh_mutex));
2885 n->status.blacklisted = false;
2887 if(n->status.reachable) {
2888 update_node_status(mesh, n);
2891 //Remove blacklisting from the config file
2892 append_config_file(mesh, n->name, "blacklisted", NULL);
2894 pthread_mutex_unlock(&(mesh->mesh_mutex));
2898 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2899 mesh->default_blacklist = blacklist;
2902 /* Hint that a hostname may be found at an address
2903 * See header file for detailed comment.
2905 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2906 if(!mesh || !node || !addr) {
2910 // Ignore hints about ourself.
2911 if((node_t *)node == mesh->self) {
2915 pthread_mutex_lock(&(mesh->mesh_mutex));
2917 char *host = NULL, *port = NULL, *str = NULL;
2918 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2921 xasprintf(&str, "%s %s", host, port);
2923 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2924 modify_config_file(mesh, node->name, "Address", str, 5);
2926 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2934 pthread_mutex_unlock(&(mesh->mesh_mutex));
2935 // @TODO do we want to fire off a connection attempt right away?
2938 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2940 node_t *n = utcp->priv;
2941 meshlink_handle_t *mesh = n->mesh;
2942 return mesh->channel_accept_cb;
2945 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2946 meshlink_channel_t *channel = connection->priv;
2952 node_t *n = channel->node;
2953 meshlink_handle_t *mesh = n->mesh;
2955 if(n->status.destroyed) {
2956 meshlink_channel_close(mesh, channel);
2957 } else if(channel->receive_cb) {
2958 channel->receive_cb(mesh, channel, data, len);
2964 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2965 node_t *n = utcp_connection->utcp->priv;
2971 meshlink_handle_t *mesh = n->mesh;
2973 if(!mesh->channel_accept_cb) {
2977 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2979 channel->c = utcp_connection;
2981 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2982 utcp_accept(utcp_connection, channel_recv, channel);
2988 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2989 node_t *n = utcp->priv;
2991 if(n->status.destroyed) {
2995 meshlink_handle_t *mesh = n->mesh;
2996 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2999 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3000 if(!mesh || !channel) {
3001 meshlink_errno = MESHLINK_EINVAL;
3005 channel->receive_cb = cb;
3008 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3010 node_t *n = (node_t *)source;
3016 utcp_recv(n->utcp, data, len);
3019 static void channel_poll(struct utcp_connection *connection, size_t len) {
3020 meshlink_channel_t *channel = connection->priv;
3026 node_t *n = channel->node;
3027 meshlink_handle_t *mesh = n->mesh;
3029 if(channel->poll_cb) {
3030 channel->poll_cb(mesh, channel, len);
3034 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3036 channel->poll_cb = cb;
3037 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
3040 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3042 meshlink_errno = MESHLINK_EINVAL;
3046 pthread_mutex_lock(&mesh->mesh_mutex);
3047 mesh->channel_accept_cb = cb;
3048 mesh->receive_cb = channel_receive;
3050 for splay_each(node_t, n, mesh->nodes) {
3051 if(!n->utcp && n != mesh->self) {
3052 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3056 pthread_mutex_unlock(&mesh->mesh_mutex);
3059 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) {
3061 abort(); // TODO: handle non-NULL data
3064 if(!mesh || !node) {
3065 meshlink_errno = MESHLINK_EINVAL;
3069 node_t *n = (node_t *)node;
3072 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3073 mesh->receive_cb = channel_receive;
3076 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3081 if(n->status.blacklisted) {
3082 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3086 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3088 channel->receive_cb = cb;
3089 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3092 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3100 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) {
3101 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3104 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3105 if(!mesh || !channel) {
3106 meshlink_errno = MESHLINK_EINVAL;
3110 utcp_shutdown(channel->c, direction);
3113 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3114 if(!mesh || !channel) {
3115 meshlink_errno = MESHLINK_EINVAL;
3119 utcp_close(channel->c);
3123 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3124 if(!mesh || !channel) {
3125 meshlink_errno = MESHLINK_EINVAL;
3134 meshlink_errno = MESHLINK_EINVAL;
3138 // TODO: more finegrained locking.
3139 // Ideally we want to put the data into the UTCP connection's send buffer.
3140 // Then, preferrably only if there is room in the receiver window,
3141 // kick the meshlink thread to go send packets.
3143 pthread_mutex_lock(&mesh->mesh_mutex);
3144 ssize_t retval = utcp_send(channel->c, data, len);
3145 pthread_mutex_unlock(&mesh->mesh_mutex);
3148 meshlink_errno = MESHLINK_ENETWORK;
3154 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3155 if(!mesh || !channel) {
3156 meshlink_errno = MESHLINK_EINVAL;
3160 return channel->c->flags;
3163 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3164 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3165 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3168 if(mesh->node_status_cb) {
3169 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3173 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3174 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3178 n->status.duplicate = true;
3179 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3182 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3186 meshlink_errno = MESHLINK_EINVAL;
3190 pthread_mutex_lock(&mesh->mesh_mutex);
3192 if(mesh->discovery == enable) {
3196 if(mesh->threadstarted) {
3198 discovery_start(mesh);
3200 discovery_stop(mesh);
3204 mesh->discovery = enable;
3207 pthread_mutex_unlock(&mesh->mesh_mutex);
3211 meshlink_errno = MESHLINK_ENOTSUP;
3215 static void __attribute__((constructor)) meshlink_init(void) {
3218 randomize(&seed, sizeof(seed));
3222 static void __attribute__((destructor)) meshlink_exit(void) {
3226 /// Device class traits
3227 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3228 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3229 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3230 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3231 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN