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 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
631 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
638 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
651 int check_port(meshlink_handle_t *mesh) {
652 for(int i = 0; i < 1000; i++) {
653 int port = 0x1000 + (rand() & 0x7fff);
656 char filename[PATH_MAX];
657 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
658 FILE *f = fopen(filename, "a");
661 meshlink_errno = MESHLINK_ESTORAGE;
662 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
666 fprintf(f, "Port = %d\n", port);
672 meshlink_errno = MESHLINK_ENETWORK;
673 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
677 static void deltree(const char *dirname) {
678 DIR *d = opendir(dirname);
683 while((ent = readdir(d))) {
684 if(ent->d_name[0] == '.') {
688 char filename[PATH_MAX];
689 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
691 if(unlink(filename)) {
702 static bool finalize_join(meshlink_handle_t *mesh) {
703 char *name = xstrdup(get_value(mesh->data, "Name"));
706 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
710 if(!check_id(name)) {
711 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
715 char filename[PATH_MAX];
716 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
718 FILE *f = fopen(filename, "w");
721 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
725 fprintf(f, "Name = %s\n", name);
727 // Wipe all old host config files and invitations
728 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
731 if(mkdir(filename, 0777) && errno != EEXIST) {
732 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
736 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
739 // Create a new host config file for ourself
740 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
741 FILE *fh = fopen(filename, "w");
744 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
749 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
750 // Other chunks go unfiltered to their respective host config files
751 const char *p = mesh->data;
754 while((l = get_line(&p))) {
760 // Split line into variable and value
761 int len = strcspn(l, "\t =");
763 value += strspn(value, "\t ");
767 value += strspn(value, "\t ");
773 if(!strcasecmp(l, "Name"))
774 if(strcmp(value, name)) {
778 } else if(!strcasecmp(l, "NetName")) {
782 // Check the list of known variables
786 for(i = 0; variables[i].name; i++) {
787 if(strcasecmp(l, variables[i].name)) {
795 // Ignore unknown and unsafe variables
797 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
799 } else if(!(variables[i].type & VAR_SAFE)) {
800 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
804 // Copy the safe variable to the right config file
805 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
810 while(l && !strcasecmp(l, "Name")) {
811 if(!check_id(value)) {
812 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
816 if(!strcmp(value, name)) {
817 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
821 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
822 f = fopen(filename, "w");
825 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
829 while((l = get_line(&p))) {
830 if(!strcmp(l, "#---------------------------------------------------------------#")) {
834 int len = strcspn(l, "\t =");
836 if(len == 4 && !strncasecmp(l, "Name", 4)) {
838 value += strspn(value, "\t ");
842 value += strspn(value, "\t ");
856 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
863 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
864 fprintf(fh, "Port = %s\n", mesh->myport);
868 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
872 free(mesh->self->name);
873 free(mesh->self->connection->name);
874 mesh->name = xstrdup(name);
875 mesh->self->name = xstrdup(name);
876 mesh->self->connection->name = name;
878 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
880 load_all_nodes(mesh);
885 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
887 meshlink_handle_t *mesh = handle;
888 const char *ptr = data;
891 int result = send(mesh->sock, ptr, len, 0);
893 if(result == -1 && errno == EINTR) {
895 } else if(result <= 0) {
906 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
907 meshlink_handle_t *mesh = handle;
910 case SPTPS_HANDSHAKE:
911 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
914 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
915 memcpy(mesh->data + mesh->thedatalen, msg, len);
916 mesh->thedatalen += len;
917 mesh->data[mesh->thedatalen] = 0;
921 mesh->thedatalen = 0;
922 return finalize_join(mesh);
925 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
926 shutdown(mesh->sock, SHUT_RDWR);
927 mesh->success = true;
937 static bool recvline(meshlink_handle_t *mesh, size_t len) {
938 char *newline = NULL;
944 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
945 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
947 if(result == -1 && errno == EINTR) {
949 } else if(result <= 0) {
953 mesh->blen += result;
956 if((size_t)(newline - mesh->buffer) >= len) {
960 len = newline - mesh->buffer;
962 memcpy(mesh->line, mesh->buffer, len);
964 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
965 mesh->blen -= len + 1;
969 static bool sendline(int fd, char *format, ...) {
970 static char buffer[4096];
975 va_start(ap, format);
976 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
979 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
987 int result = send(fd, p, blen, MSG_NOSIGNAL);
989 if(result == -1 && errno == EINTR) {
991 } else if(result <= 0) {
1002 static const char *errstr[] = {
1003 [MESHLINK_OK] = "No error",
1004 [MESHLINK_EINVAL] = "Invalid argument",
1005 [MESHLINK_ENOMEM] = "Out of memory",
1006 [MESHLINK_ENOENT] = "No such node",
1007 [MESHLINK_EEXIST] = "Node already exists",
1008 [MESHLINK_EINTERNAL] = "Internal error",
1009 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1010 [MESHLINK_ESTORAGE] = "Storage error",
1011 [MESHLINK_ENETWORK] = "Network error",
1012 [MESHLINK_EPEER] = "Error communicating with peer",
1013 [MESHLINK_ENOTSUP] = "Operation not supported",
1014 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1017 const char *meshlink_strerror(meshlink_errno_t err) {
1018 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1019 return "Invalid error code";
1025 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1028 char pubname[PATH_MAX], privname[PATH_MAX];
1030 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1032 if(!(key = ecdsa_generate())) {
1033 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1034 meshlink_errno = MESHLINK_EINTERNAL;
1037 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1040 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1041 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1042 meshlink_errno = MESHLINK_ESTORAGE;
1046 f = fopen(privname, "wb");
1049 meshlink_errno = MESHLINK_ESTORAGE;
1054 fchmod(fileno(f), 0600);
1057 if(!ecdsa_write_pem_private_key(key, f)) {
1058 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1061 meshlink_errno = MESHLINK_EINTERNAL;
1067 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1068 f = fopen(pubname, "a");
1071 meshlink_errno = MESHLINK_ESTORAGE;
1075 char *pubkey = ecdsa_get_base64_public_key(key);
1076 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1085 static struct timeval idle(event_loop_t *loop, void *data) {
1087 meshlink_handle_t *mesh = data;
1088 struct timeval t, tmin = {3600, 0};
1090 for splay_each(node_t, n, mesh->nodes) {
1095 t = utcp_timeout(n->utcp);
1097 if(timercmp(&t, &tmin, <)) {
1105 // Get our local address(es) by simulating connecting to an Internet host.
1106 static void add_local_addresses(meshlink_handle_t *mesh) {
1107 char host[NI_MAXHOST];
1108 char entry[MAX_STRING_SIZE];
1112 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1113 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1114 append_config_file(mesh, mesh->name, "Address", entry);
1119 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1120 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1121 append_config_file(mesh, mesh->name, "Address", entry);
1125 static bool meshlink_setup(meshlink_handle_t *mesh) {
1126 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1127 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1128 meshlink_errno = MESHLINK_ESTORAGE;
1132 char filename[PATH_MAX];
1133 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1135 if(mkdir(filename, 0777) && errno != EEXIST) {
1136 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1137 meshlink_errno = MESHLINK_ESTORAGE;
1141 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1143 if(!access(filename, F_OK)) {
1144 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1145 meshlink_errno = MESHLINK_EEXIST;
1149 FILE *f = fopen(filename, "w");
1152 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1153 meshlink_errno = MESHLINK_ESTORAGE;
1157 fprintf(f, "Name = %s\n", mesh->name);
1160 if(!ecdsa_keygen(mesh)) {
1161 meshlink_errno = MESHLINK_EINTERNAL;
1166 if(check_port(mesh) == 0) {
1167 meshlink_errno = MESHLINK_ENETWORK;
1175 static void *setup_network_in_netns_thread(void *arg) {
1176 meshlink_handle_t *mesh = arg;
1178 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1182 bool success = setup_network(mesh);
1183 add_local_addresses(mesh);
1184 return success ? arg : NULL;
1187 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1188 if(!confbase || !*confbase) {
1189 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1190 meshlink_errno = MESHLINK_EINVAL;
1194 if(!appname || !*appname) {
1195 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1196 meshlink_errno = MESHLINK_EINVAL;
1200 if(strchr(appname, ' ')) {
1201 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1202 meshlink_errno = MESHLINK_EINVAL;
1206 if(!name || !*name) {
1207 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1209 } else { //check name only if there is a name != NULL
1210 if(!check_id(name)) {
1211 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1212 meshlink_errno = MESHLINK_EINVAL;
1217 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1218 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1219 meshlink_errno = MESHLINK_EINVAL;
1223 meshlink_open_params_t *params = xzalloc(sizeof * params);
1225 params->confbase = xstrdup(confbase);
1226 params->name = xstrdup(name);
1227 params->appname = xstrdup(appname);
1228 params->devclass = devclass;
1234 void meshlink_open_params_free(meshlink_open_params_t *params) {
1236 meshlink_errno = MESHLINK_EINVAL;
1240 free(params->confbase);
1242 free(params->appname);
1247 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1248 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1249 meshlink_open_params_t params = {NULL};
1251 params.confbase = (char *)confbase;
1252 params.name = (char *)name;
1253 params.appname = (char *)appname;
1254 params.devclass = devclass;
1257 return meshlink_open_ex(¶ms);
1259 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1260 // Validate arguments provided by the application
1261 bool usingname = false;
1263 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1265 if(!params->confbase || !*params->confbase) {
1266 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1267 meshlink_errno = MESHLINK_EINVAL;
1271 if(!params->appname || !*params->appname) {
1272 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1273 meshlink_errno = MESHLINK_EINVAL;
1277 if(strchr(params->appname, ' ')) {
1278 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1279 meshlink_errno = MESHLINK_EINVAL;
1283 if(!params->name || !*params->name) {
1284 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1286 } else { //check name only if there is a name != NULL
1288 if(!check_id(params->name)) {
1289 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1290 meshlink_errno = MESHLINK_EINVAL;
1297 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1298 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1299 meshlink_errno = MESHLINK_EINVAL;
1303 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1304 mesh->confbase = xstrdup(params->confbase);
1305 mesh->appname = xstrdup(params->appname);
1306 mesh->devclass = params->devclass;
1307 mesh->discovery = true;
1308 mesh->invitation_timeout = 604800; // 1 week
1309 mesh->netns = params->netns;
1310 mesh->submeshes = NULL;
1313 mesh->name = xstrdup(params->name);
1317 pthread_mutexattr_t attr;
1318 pthread_mutexattr_init(&attr);
1319 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1320 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1322 mesh->threadstarted = false;
1323 event_loop_init(&mesh->loop);
1324 mesh->loop.data = mesh;
1326 meshlink_queue_init(&mesh->outpacketqueue);
1328 // Check whether meshlink.conf already exists
1330 char filename[PATH_MAX];
1331 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1333 if(access(filename, R_OK)) {
1334 if(errno == ENOENT) {
1335 // If not, create it
1336 if(!meshlink_setup(mesh)) {
1337 // meshlink_errno is set by meshlink_setup()
1341 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1342 meshlink_close(mesh);
1343 meshlink_errno = MESHLINK_ESTORAGE;
1348 // Open the configuration file and lock it
1350 mesh->conffile = fopen(filename, "r");
1352 if(!mesh->conffile) {
1353 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1354 meshlink_close(mesh);
1355 meshlink_errno = MESHLINK_ESTORAGE;
1360 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1364 // TODO: use _locking()?
1367 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1368 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1369 meshlink_close(mesh);
1370 meshlink_errno = MESHLINK_EBUSY;
1376 // Read the configuration
1378 init_configuration(&mesh->config);
1380 if(!read_server_config(mesh)) {
1381 meshlink_close(mesh);
1382 meshlink_errno = MESHLINK_ESTORAGE;
1387 struct WSAData wsa_state;
1389 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1393 // Setup up everything
1394 // TODO: we should not open listening sockets yet
1396 bool success = false;
1398 if(mesh->netns != -1) {
1401 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1402 void *retval = NULL;
1403 success = pthread_join(thr, &retval) == 0 && retval;
1406 success = setup_network(mesh);
1407 add_local_addresses(mesh);
1411 meshlink_close(mesh);
1412 meshlink_errno = MESHLINK_ENETWORK;
1416 idle_set(&mesh->loop, idle, mesh);
1418 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1422 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1423 meshlink_submesh_t *s = NULL;
1426 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1427 meshlink_errno = MESHLINK_EINVAL;
1431 if(!submesh || !*submesh) {
1432 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1433 meshlink_errno = MESHLINK_EINVAL;
1438 pthread_mutex_lock(&(mesh->mesh_mutex));
1440 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1442 pthread_mutex_unlock(&(mesh->mesh_mutex));
1447 static void *meshlink_main_loop(void *arg) {
1448 meshlink_handle_t *mesh = arg;
1450 if(mesh->netns != -1) {
1451 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1456 pthread_mutex_lock(&(mesh->mesh_mutex));
1458 try_outgoing_connections(mesh);
1460 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1462 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1464 pthread_mutex_unlock(&(mesh->mesh_mutex));
1468 bool meshlink_start(meshlink_handle_t *mesh) {
1470 meshlink_errno = MESHLINK_EINVAL;
1474 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1476 pthread_mutex_lock(&(mesh->mesh_mutex));
1478 if(mesh->threadstarted) {
1479 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1480 pthread_mutex_unlock(&(mesh->mesh_mutex));
1484 if(mesh->listen_socket[0].tcp.fd < 0) {
1485 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1486 meshlink_errno = MESHLINK_ENETWORK;
1490 mesh->thedatalen = 0;
1492 // TODO: open listening sockets first
1494 //Check that a valid name is set
1496 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1497 meshlink_errno = MESHLINK_EINVAL;
1498 pthread_mutex_unlock(&(mesh->mesh_mutex));
1502 // Start the main thread
1504 event_loop_start(&mesh->loop);
1506 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1507 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1508 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1509 meshlink_errno = MESHLINK_EINTERNAL;
1510 event_loop_stop(&mesh->loop);
1511 pthread_mutex_unlock(&(mesh->mesh_mutex));
1515 mesh->threadstarted = true;
1519 if(mesh->discovery) {
1520 discovery_start(mesh);
1525 pthread_mutex_unlock(&(mesh->mesh_mutex));
1529 void meshlink_stop(meshlink_handle_t *mesh) {
1531 meshlink_errno = MESHLINK_EINVAL;
1535 pthread_mutex_lock(&(mesh->mesh_mutex));
1536 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1541 if(mesh->discovery) {
1542 discovery_stop(mesh);
1547 // Shut down the main thread
1548 event_loop_stop(&mesh->loop);
1550 // Send ourselves a UDP packet to kick the event loop
1551 for(int i = 0; i < mesh->listen_sockets; i++) {
1553 socklen_t salen = sizeof(sa.sa);
1555 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1556 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1560 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1561 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1565 if(mesh->threadstarted) {
1566 // Wait for the main thread to finish
1567 pthread_mutex_unlock(&(mesh->mesh_mutex));
1568 pthread_join(mesh->thread, NULL);
1569 pthread_mutex_lock(&(mesh->mesh_mutex));
1571 mesh->threadstarted = false;
1574 // Close all metaconnections
1575 if(mesh->connections) {
1576 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1578 connection_t *c = node->data;
1580 terminate_connection(mesh, c, false);
1584 if(mesh->outgoings) {
1585 list_delete_list(mesh->outgoings);
1586 mesh->outgoings = NULL;
1589 pthread_mutex_unlock(&(mesh->mesh_mutex));
1592 void meshlink_close(meshlink_handle_t *mesh) {
1593 if(!mesh || !mesh->confbase) {
1594 meshlink_errno = MESHLINK_EINVAL;
1598 // stop can be called even if mesh has not been started
1599 meshlink_stop(mesh);
1601 // lock is not released after this
1602 pthread_mutex_lock(&(mesh->mesh_mutex));
1604 // Close and free all resources used.
1606 close_network_connections(mesh);
1608 logger(mesh, MESHLINK_INFO, "Terminating");
1610 exit_configuration(&mesh->config);
1611 event_loop_exit(&mesh->loop);
1615 if(mesh->confbase) {
1621 ecdsa_free(mesh->invitation_key);
1623 if(mesh->netns != -1) {
1628 free(mesh->appname);
1629 free(mesh->confbase);
1630 pthread_mutex_destroy(&(mesh->mesh_mutex));
1632 if(mesh->conffile) {
1633 fclose(mesh->conffile);
1636 memset(mesh, 0, sizeof(*mesh));
1641 bool meshlink_destroy(const char *confbase) {
1643 meshlink_errno = MESHLINK_EINVAL;
1647 char filename[PATH_MAX];
1648 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1650 if(unlink(filename)) {
1651 if(errno == ENOENT) {
1652 meshlink_errno = MESHLINK_ENOENT;
1655 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1656 meshlink_errno = MESHLINK_ESTORAGE;
1666 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1668 meshlink_errno = MESHLINK_EINVAL;
1672 pthread_mutex_lock(&(mesh->mesh_mutex));
1673 mesh->receive_cb = cb;
1674 pthread_mutex_unlock(&(mesh->mesh_mutex));
1677 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1679 meshlink_errno = MESHLINK_EINVAL;
1683 pthread_mutex_lock(&(mesh->mesh_mutex));
1684 mesh->node_status_cb = cb;
1685 pthread_mutex_unlock(&(mesh->mesh_mutex));
1688 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1690 meshlink_errno = MESHLINK_EINVAL;
1694 pthread_mutex_lock(&(mesh->mesh_mutex));
1695 mesh->node_duplicate_cb = cb;
1696 pthread_mutex_unlock(&(mesh->mesh_mutex));
1699 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1701 pthread_mutex_lock(&(mesh->mesh_mutex));
1703 mesh->log_level = cb ? level : 0;
1704 pthread_mutex_unlock(&(mesh->mesh_mutex));
1707 global_log_level = cb ? level : 0;
1711 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1712 meshlink_packethdr_t *hdr;
1714 // Validate arguments
1715 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1716 meshlink_errno = MESHLINK_EINVAL;
1725 meshlink_errno = MESHLINK_EINVAL;
1729 node_t *n = (node_t *)destination;
1731 if(n->status.blacklisted) {
1732 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1736 // Prepare the packet
1737 vpn_packet_t *packet = malloc(sizeof(*packet));
1740 meshlink_errno = MESHLINK_ENOMEM;
1744 packet->probe = false;
1745 packet->tcp = false;
1746 packet->len = len + sizeof(*hdr);
1748 hdr = (meshlink_packethdr_t *)packet->data;
1749 memset(hdr, 0, sizeof(*hdr));
1750 // leave the last byte as 0 to make sure strings are always
1751 // null-terminated if they are longer than the buffer
1752 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1753 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1755 memcpy(packet->data + sizeof(*hdr), data, len);
1758 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1760 meshlink_errno = MESHLINK_ENOMEM;
1764 // Notify event loop
1765 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1770 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1772 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1778 mesh->self->in_packets++;
1779 mesh->self->in_bytes += packet->len;
1780 route(mesh, mesh->self, packet);
1783 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1784 if(!mesh || !destination) {
1785 meshlink_errno = MESHLINK_EINVAL;
1789 pthread_mutex_lock(&(mesh->mesh_mutex));
1791 node_t *n = (node_t *)destination;
1793 if(!n->status.reachable) {
1794 pthread_mutex_unlock(&(mesh->mesh_mutex));
1797 } else if(n->mtuprobes > 30 && n->minmtu) {
1798 pthread_mutex_unlock(&(mesh->mesh_mutex));
1801 pthread_mutex_unlock(&(mesh->mesh_mutex));
1806 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1807 if(!mesh || !node) {
1808 meshlink_errno = MESHLINK_EINVAL;
1812 pthread_mutex_lock(&(mesh->mesh_mutex));
1814 node_t *n = (node_t *)node;
1816 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1817 meshlink_errno = MESHLINK_EINTERNAL;
1818 pthread_mutex_unlock(&(mesh->mesh_mutex));
1822 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1825 meshlink_errno = MESHLINK_EINTERNAL;
1828 pthread_mutex_unlock(&(mesh->mesh_mutex));
1832 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1834 meshlink_errno = MESHLINK_EINVAL;
1838 return (meshlink_node_t *)mesh->self;
1841 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1842 if(!mesh || !name) {
1843 meshlink_errno = MESHLINK_EINVAL;
1847 meshlink_node_t *node = NULL;
1849 pthread_mutex_lock(&(mesh->mesh_mutex));
1850 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1851 pthread_mutex_unlock(&(mesh->mesh_mutex));
1855 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1856 if(!mesh || !name) {
1857 meshlink_errno = MESHLINK_EINVAL;
1861 meshlink_submesh_t *submesh = NULL;
1863 pthread_mutex_lock(&(mesh->mesh_mutex));
1864 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1865 pthread_mutex_unlock(&(mesh->mesh_mutex));
1869 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1870 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1871 meshlink_errno = MESHLINK_EINVAL;
1875 meshlink_node_t **result;
1878 pthread_mutex_lock(&(mesh->mesh_mutex));
1880 *nmemb = mesh->nodes->count;
1881 result = realloc(nodes, *nmemb * sizeof(*nodes));
1884 meshlink_node_t **p = result;
1886 for splay_each(node_t, n, mesh->nodes) {
1887 *p++ = (meshlink_node_t *)n;
1892 meshlink_errno = MESHLINK_ENOMEM;
1895 pthread_mutex_unlock(&(mesh->mesh_mutex));
1900 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) {
1901 meshlink_node_t **result;
1903 pthread_mutex_lock(&(mesh->mesh_mutex));
1907 for splay_each(node_t, n, mesh->nodes) {
1908 if(true == search_node(n, condition)) {
1909 *nmemb = *nmemb + 1;
1915 pthread_mutex_unlock(&(mesh->mesh_mutex));
1919 result = realloc(nodes, *nmemb * sizeof(*nodes));
1922 meshlink_node_t **p = result;
1924 for splay_each(node_t, n, mesh->nodes) {
1925 if(true == search_node(n, condition)) {
1926 *p++ = (meshlink_node_t *)n;
1932 meshlink_errno = MESHLINK_ENOMEM;
1935 pthread_mutex_unlock(&(mesh->mesh_mutex));
1940 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1941 dev_class_t *devclass = (dev_class_t *)condition;
1943 if(*devclass == node->devclass) {
1950 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1951 if(condition == node->submesh) {
1958 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) {
1959 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1960 meshlink_errno = MESHLINK_EINVAL;
1964 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1967 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1968 if(!mesh || !submesh || !nmemb) {
1969 meshlink_errno = MESHLINK_EINVAL;
1973 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1976 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1977 if(!mesh || !node) {
1978 meshlink_errno = MESHLINK_EINVAL;
1982 dev_class_t devclass;
1984 pthread_mutex_lock(&(mesh->mesh_mutex));
1986 devclass = ((node_t *)node)->devclass;
1988 pthread_mutex_unlock(&(mesh->mesh_mutex));
1993 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1994 if(!mesh || !node) {
1995 meshlink_errno = MESHLINK_EINVAL;
1999 node_t *n = (node_t *)node;
2001 meshlink_submesh_t *s;
2003 s = (meshlink_submesh_t *)n->submesh;
2008 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2009 if(!mesh || !data || !len || !signature || !siglen) {
2010 meshlink_errno = MESHLINK_EINVAL;
2014 if(*siglen < MESHLINK_SIGLEN) {
2015 meshlink_errno = MESHLINK_EINVAL;
2019 pthread_mutex_lock(&(mesh->mesh_mutex));
2021 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
2022 meshlink_errno = MESHLINK_EINTERNAL;
2023 pthread_mutex_unlock(&(mesh->mesh_mutex));
2027 *siglen = MESHLINK_SIGLEN;
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2032 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2033 if(!mesh || !data || !len || !signature) {
2034 meshlink_errno = MESHLINK_EINVAL;
2038 if(siglen != MESHLINK_SIGLEN) {
2039 meshlink_errno = MESHLINK_EINVAL;
2043 pthread_mutex_lock(&(mesh->mesh_mutex));
2047 struct node_t *n = (struct node_t *)source;
2048 node_read_ecdsa_public_key(mesh, n);
2051 meshlink_errno = MESHLINK_EINTERNAL;
2054 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2057 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2062 char filename[PATH_MAX];
2064 pthread_mutex_lock(&(mesh->mesh_mutex));
2066 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2068 if(mkdir(filename, 0700) && errno != EEXIST) {
2069 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2070 meshlink_errno = MESHLINK_ESTORAGE;
2071 pthread_mutex_unlock(&(mesh->mesh_mutex));
2075 // Count the number of valid invitations, clean up old ones
2076 DIR *dir = opendir(filename);
2079 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2080 meshlink_errno = MESHLINK_ESTORAGE;
2081 pthread_mutex_unlock(&(mesh->mesh_mutex));
2088 time_t deadline = time(NULL) - 604800; // 1 week in the past
2090 while((ent = readdir(dir))) {
2091 if(strlen(ent->d_name) != 24) {
2095 char invname[PATH_MAX];
2098 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2099 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2103 if(!stat(invname, &st)) {
2104 if(mesh->invitation_key && deadline < st.st_mtime) {
2110 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2116 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2118 meshlink_errno = MESHLINK_ESTORAGE;
2119 pthread_mutex_unlock(&(mesh->mesh_mutex));
2125 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2127 // Remove the key if there are no outstanding invitations.
2131 if(mesh->invitation_key) {
2132 ecdsa_free(mesh->invitation_key);
2133 mesh->invitation_key = NULL;
2137 if(mesh->invitation_key) {
2138 pthread_mutex_unlock(&(mesh->mesh_mutex));
2142 // Create a new key if necessary.
2143 FILE *f = fopen(filename, "rb");
2146 if(errno != ENOENT) {
2147 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2148 meshlink_errno = MESHLINK_ESTORAGE;
2149 pthread_mutex_unlock(&(mesh->mesh_mutex));
2153 mesh->invitation_key = ecdsa_generate();
2155 if(!mesh->invitation_key) {
2156 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2157 meshlink_errno = MESHLINK_EINTERNAL;
2158 pthread_mutex_unlock(&(mesh->mesh_mutex));
2162 f = fopen(filename, "wb");
2165 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2166 meshlink_errno = MESHLINK_ESTORAGE;
2167 pthread_mutex_unlock(&(mesh->mesh_mutex));
2171 chmod(filename, 0600);
2172 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2175 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2178 if(!mesh->invitation_key) {
2179 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2180 meshlink_errno = MESHLINK_ESTORAGE;
2184 pthread_mutex_unlock(&(mesh->mesh_mutex));
2185 return mesh->invitation_key;
2188 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2189 if(!mesh || !node || !address) {
2190 meshlink_errno = MESHLINK_EINVAL;
2194 if(!is_valid_hostname(address)) {
2195 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2196 meshlink_errno = MESHLINK_EINVAL;
2200 if(port && !is_valid_port(port)) {
2201 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2202 meshlink_errno = MESHLINK_EINVAL;
2206 char *canonical_address;
2209 xasprintf(&canonical_address, "%s %s", address, port);
2211 canonical_address = xstrdup(address);
2214 pthread_mutex_lock(&(mesh->mesh_mutex));
2215 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2216 pthread_mutex_unlock(&(mesh->mesh_mutex));
2218 free(canonical_address);
2222 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2223 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2226 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2228 meshlink_errno = MESHLINK_EINVAL;
2232 char *address = meshlink_get_external_address(mesh);
2240 pthread_mutex_lock(&(mesh->mesh_mutex));
2241 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2242 pthread_mutex_unlock(&(mesh->mesh_mutex));
2248 int meshlink_get_port(meshlink_handle_t *mesh) {
2250 meshlink_errno = MESHLINK_EINVAL;
2255 meshlink_errno = MESHLINK_EINTERNAL;
2259 return atoi(mesh->myport);
2262 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2263 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2264 meshlink_errno = MESHLINK_EINVAL;
2268 if(mesh->myport && port == atoi(mesh->myport)) {
2272 if(!try_bind(port)) {
2273 meshlink_errno = MESHLINK_ENETWORK;
2279 pthread_mutex_lock(&(mesh->mesh_mutex));
2281 if(mesh->threadstarted) {
2282 meshlink_errno = MESHLINK_EINVAL;
2286 close_network_connections(mesh);
2287 exit_configuration(&mesh->config);
2290 snprintf(portstr, sizeof(portstr), "%d", port);
2291 portstr[sizeof(portstr) - 1] = 0;
2293 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2295 init_configuration(&mesh->config);
2297 if(!read_server_config(mesh)) {
2298 meshlink_errno = MESHLINK_ESTORAGE;
2299 } else if(!setup_network(mesh)) {
2300 meshlink_errno = MESHLINK_ENETWORK;
2306 pthread_mutex_unlock(&(mesh->mesh_mutex));
2311 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2312 mesh->invitation_timeout = timeout;
2315 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2316 meshlink_submesh_t *s = NULL;
2319 meshlink_errno = MESHLINK_EINVAL;
2324 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2327 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2328 meshlink_errno = MESHLINK_EINVAL;
2332 s = (meshlink_submesh_t *)mesh->self->submesh;
2335 pthread_mutex_lock(&(mesh->mesh_mutex));
2337 // Check validity of the new node's name
2338 if(!check_id(name)) {
2339 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2340 meshlink_errno = MESHLINK_EINVAL;
2341 pthread_mutex_unlock(&(mesh->mesh_mutex));
2345 // Ensure no host configuration file with that name exists
2346 char filename[PATH_MAX];
2347 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2349 if(!access(filename, F_OK)) {
2350 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2351 meshlink_errno = MESHLINK_EEXIST;
2352 pthread_mutex_unlock(&(mesh->mesh_mutex));
2356 // Ensure no other nodes know about this name
2357 if(meshlink_get_node(mesh, name)) {
2358 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2359 meshlink_errno = MESHLINK_EEXIST;
2360 pthread_mutex_unlock(&(mesh->mesh_mutex));
2364 // Get the local address
2365 char *address = get_my_hostname(mesh, flags);
2368 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2369 meshlink_errno = MESHLINK_ERESOLV;
2370 pthread_mutex_unlock(&(mesh->mesh_mutex));
2374 if(!refresh_invitation_key(mesh)) {
2375 meshlink_errno = MESHLINK_EINTERNAL;
2376 pthread_mutex_unlock(&(mesh->mesh_mutex));
2382 // Create a hash of the key.
2383 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2384 sha512(fingerprint, strlen(fingerprint), hash);
2385 b64encode_urlsafe(hash, hash, 18);
2387 // Create a random cookie for this invitation.
2389 randomize(cookie, 18);
2391 // Create a filename that doesn't reveal the cookie itself
2392 char buf[18 + strlen(fingerprint)];
2393 char cookiehash[64];
2394 memcpy(buf, cookie, 18);
2395 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2396 sha512(buf, sizeof(buf), cookiehash);
2397 b64encode_urlsafe(cookiehash, cookiehash, 18);
2399 b64encode_urlsafe(cookie, cookie, 18);
2403 // Create a file containing the details of the invitation.
2404 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2405 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2408 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2409 meshlink_errno = MESHLINK_ESTORAGE;
2410 pthread_mutex_unlock(&(mesh->mesh_mutex));
2414 FILE *f = fdopen(ifd, "w");
2420 // Fill in the details.
2421 fprintf(f, "Name = %s\n", name);
2424 fprintf(f, "SubMesh = %s\n", s->name);
2427 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2429 // Copy Broadcast and Mode
2430 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2431 FILE *tc = fopen(filename, "r");
2436 while(fgets(buf, sizeof(buf), tc)) {
2437 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2438 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2441 // Make sure there is a newline character.
2442 if(!strchr(buf, '\n')) {
2450 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2451 meshlink_errno = MESHLINK_ESTORAGE;
2452 pthread_mutex_unlock(&(mesh->mesh_mutex));
2456 fprintf(f, "#---------------------------------------------------------------#\n");
2457 fprintf(f, "Name = %s\n", mesh->self->name);
2459 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2463 // Create an URL from the local address, key hash and cookie
2465 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2468 pthread_mutex_unlock(&(mesh->mesh_mutex));
2472 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2473 return meshlink_invite_ex(mesh, submesh, name, 0);
2476 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2477 if(!mesh || !invitation) {
2478 meshlink_errno = MESHLINK_EINVAL;
2482 pthread_mutex_lock(&(mesh->mesh_mutex));
2484 //Before doing meshlink_join make sure we are not connected to another mesh
2485 if(mesh->threadstarted) {
2486 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2487 meshlink_errno = MESHLINK_EINVAL;
2488 pthread_mutex_unlock(&(mesh->mesh_mutex));
2492 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2493 char copy[strlen(invitation) + 1];
2494 strcpy(copy, invitation);
2496 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2498 char *slash = strchr(copy, '/');
2506 if(strlen(slash) != 48) {
2510 char *address = copy;
2513 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2517 // Generate a throw-away key for the invitation.
2518 ecdsa_t *key = ecdsa_generate();
2521 meshlink_errno = MESHLINK_EINTERNAL;
2522 pthread_mutex_unlock(&(mesh->mesh_mutex));
2526 char *b64key = ecdsa_get_base64_public_key(key);
2530 while(address && *address) {
2531 // We allow commas in the address part to support multiple addresses in one invitation URL.
2532 comma = strchr(address, ',');
2538 // Split of the port
2539 port = strrchr(address, ':');
2547 // IPv6 address are enclosed in brackets, per RFC 3986
2548 if(*address == '[') {
2550 char *bracket = strchr(address, ']');
2563 // Connect to the meshlink daemon mentioned in the URL.
2564 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2567 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2568 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2570 if(mesh->sock == -1) {
2571 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2572 meshlink_errno = MESHLINK_ENETWORK;
2576 set_timeout(mesh->sock, 5000);
2578 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2579 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2580 meshlink_errno = MESHLINK_ENETWORK;
2581 closesocket(mesh->sock);
2589 meshlink_errno = MESHLINK_ERESOLV;
2592 if(mesh->sock != -1 || !comma) {
2599 if(mesh->sock == -1) {
2600 pthread_mutex_unlock(&mesh->mesh_mutex);
2604 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2606 // Tell him we have an invitation, and give him our throw-away key.
2610 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2611 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2612 closesocket(mesh->sock);
2613 meshlink_errno = MESHLINK_ENETWORK;
2614 pthread_mutex_unlock(&(mesh->mesh_mutex));
2620 char hisname[4096] = "";
2621 int code, hismajor, hisminor = 0;
2623 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) {
2624 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2625 closesocket(mesh->sock);
2626 meshlink_errno = MESHLINK_ENETWORK;
2627 pthread_mutex_unlock(&(mesh->mesh_mutex));
2631 // Check if the hash of the key he gave us matches the hash in the URL.
2632 char *fingerprint = mesh->line + 2;
2635 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2636 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2637 meshlink_errno = MESHLINK_EINTERNAL;
2638 pthread_mutex_unlock(&(mesh->mesh_mutex));
2642 if(memcmp(hishash, mesh->hash, 18)) {
2643 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2644 meshlink_errno = MESHLINK_EPEER;
2645 pthread_mutex_unlock(&(mesh->mesh_mutex));
2650 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2653 meshlink_errno = MESHLINK_EINTERNAL;
2654 pthread_mutex_unlock(&(mesh->mesh_mutex));
2658 // Start an SPTPS session
2659 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2660 meshlink_errno = MESHLINK_EINTERNAL;
2661 pthread_mutex_unlock(&(mesh->mesh_mutex));
2665 // Feed rest of input buffer to SPTPS
2666 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2667 meshlink_errno = MESHLINK_EPEER;
2668 pthread_mutex_unlock(&(mesh->mesh_mutex));
2674 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2676 if(errno == EINTR) {
2680 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2681 meshlink_errno = MESHLINK_ENETWORK;
2682 pthread_mutex_unlock(&(mesh->mesh_mutex));
2686 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2687 meshlink_errno = MESHLINK_EPEER;
2688 pthread_mutex_unlock(&(mesh->mesh_mutex));
2693 sptps_stop(&mesh->sptps);
2696 closesocket(mesh->sock);
2698 if(!mesh->success) {
2699 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2700 meshlink_errno = MESHLINK_EPEER;
2701 pthread_mutex_unlock(&(mesh->mesh_mutex));
2705 pthread_mutex_unlock(&(mesh->mesh_mutex));
2709 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2710 meshlink_errno = MESHLINK_EINVAL;
2711 pthread_mutex_unlock(&(mesh->mesh_mutex));
2715 char *meshlink_export(meshlink_handle_t *mesh) {
2717 meshlink_errno = MESHLINK_EINVAL;
2721 pthread_mutex_lock(&(mesh->mesh_mutex));
2723 char filename[PATH_MAX];
2724 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2725 FILE *f = fopen(filename, "r");
2728 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2729 meshlink_errno = MESHLINK_ESTORAGE;
2730 pthread_mutex_unlock(&(mesh->mesh_mutex));
2734 fseek(f, 0, SEEK_END);
2735 int fsize = ftell(f);
2738 size_t len = fsize + 9 + strlen(mesh->self->name);
2739 char *buf = xmalloc(len);
2740 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2742 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2743 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2746 meshlink_errno = MESHLINK_ESTORAGE;
2747 pthread_mutex_unlock(&(mesh->mesh_mutex));
2754 pthread_mutex_unlock(&(mesh->mesh_mutex));
2758 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2759 if(!mesh || !data) {
2760 meshlink_errno = MESHLINK_EINVAL;
2764 pthread_mutex_lock(&(mesh->mesh_mutex));
2766 if(strncmp(data, "Name = ", 7)) {
2767 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2768 meshlink_errno = MESHLINK_EPEER;
2769 pthread_mutex_unlock(&(mesh->mesh_mutex));
2773 char *end = strchr(data + 7, '\n');
2776 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2777 meshlink_errno = MESHLINK_EPEER;
2778 pthread_mutex_unlock(&(mesh->mesh_mutex));
2782 int len = end - (data + 7);
2784 memcpy(name, data + 7, len);
2787 if(!check_id(name)) {
2788 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2789 meshlink_errno = MESHLINK_EPEER;
2790 pthread_mutex_unlock(&(mesh->mesh_mutex));
2794 char filename[PATH_MAX];
2795 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2797 if(!access(filename, F_OK)) {
2798 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2799 meshlink_errno = MESHLINK_EEXIST;
2800 pthread_mutex_unlock(&(mesh->mesh_mutex));
2804 if(errno != ENOENT) {
2805 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2806 meshlink_errno = MESHLINK_ESTORAGE;
2807 pthread_mutex_unlock(&(mesh->mesh_mutex));
2811 FILE *f = fopen(filename, "w");
2814 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2815 meshlink_errno = MESHLINK_ESTORAGE;
2816 pthread_mutex_unlock(&(mesh->mesh_mutex));
2820 fwrite(end + 1, strlen(end + 1), 1, f);
2823 load_all_nodes(mesh);
2825 pthread_mutex_unlock(&(mesh->mesh_mutex));
2829 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2830 if(!mesh || !node) {
2831 meshlink_errno = MESHLINK_EINVAL;
2835 pthread_mutex_lock(&(mesh->mesh_mutex));
2840 if(n == mesh->self) {
2841 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2842 meshlink_errno = MESHLINK_EINVAL;
2843 pthread_mutex_unlock(&(mesh->mesh_mutex));
2847 if(n->status.blacklisted) {
2848 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2849 pthread_mutex_unlock(&(mesh->mesh_mutex));
2853 n->status.blacklisted = true;
2854 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2856 //Make blacklisting persistent in the config file
2857 append_config_file(mesh, n->name, "blacklisted", "yes");
2859 //Immediately terminate any connections we have with the blacklisted node
2860 for list_each(connection_t, c, mesh->connections) {
2862 terminate_connection(mesh, c, c->status.active);
2866 utcp_abort_all_connections(n->utcp);
2872 n->status.udp_confirmed = false;
2874 if(n->status.reachable) {
2875 update_node_status(mesh, n);
2878 pthread_mutex_unlock(&(mesh->mesh_mutex));
2881 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2882 if(!mesh || !node) {
2883 meshlink_errno = MESHLINK_EINVAL;
2887 pthread_mutex_lock(&(mesh->mesh_mutex));
2889 node_t *n = (node_t *)node;
2891 if(!n->status.blacklisted) {
2892 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2893 meshlink_errno = MESHLINK_EINVAL;
2894 pthread_mutex_unlock(&(mesh->mesh_mutex));
2898 n->status.blacklisted = false;
2900 if(n->status.reachable) {
2901 update_node_status(mesh, n);
2904 //Remove blacklisting from the config file
2905 append_config_file(mesh, n->name, "blacklisted", NULL);
2907 pthread_mutex_unlock(&(mesh->mesh_mutex));
2911 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2912 mesh->default_blacklist = blacklist;
2915 /* Hint that a hostname may be found at an address
2916 * See header file for detailed comment.
2918 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2919 if(!mesh || !node || !addr) {
2923 // Ignore hints about ourself.
2924 if((node_t *)node == mesh->self) {
2928 pthread_mutex_lock(&(mesh->mesh_mutex));
2930 char *host = NULL, *port = NULL, *str = NULL;
2931 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2934 xasprintf(&str, "%s %s", host, port);
2936 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2937 modify_config_file(mesh, node->name, "Address", str, 5);
2939 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2947 pthread_mutex_unlock(&(mesh->mesh_mutex));
2948 // @TODO do we want to fire off a connection attempt right away?
2951 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2953 node_t *n = utcp->priv;
2954 meshlink_handle_t *mesh = n->mesh;
2955 return mesh->channel_accept_cb;
2958 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2959 meshlink_channel_t *channel = connection->priv;
2965 node_t *n = channel->node;
2966 meshlink_handle_t *mesh = n->mesh;
2968 if(n->status.destroyed) {
2969 meshlink_channel_close(mesh, channel);
2970 } else if(channel->receive_cb) {
2971 channel->receive_cb(mesh, channel, data, len);
2977 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2978 node_t *n = utcp_connection->utcp->priv;
2984 meshlink_handle_t *mesh = n->mesh;
2986 if(!mesh->channel_accept_cb) {
2990 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2992 channel->c = utcp_connection;
2994 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2995 utcp_accept(utcp_connection, channel_recv, channel);
3001 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3002 node_t *n = utcp->priv;
3004 if(n->status.destroyed) {
3008 meshlink_handle_t *mesh = n->mesh;
3009 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3012 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3013 if(!mesh || !channel) {
3014 meshlink_errno = MESHLINK_EINVAL;
3018 channel->receive_cb = cb;
3021 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3023 node_t *n = (node_t *)source;
3029 utcp_recv(n->utcp, data, len);
3032 static void channel_poll(struct utcp_connection *connection, size_t len) {
3033 meshlink_channel_t *channel = connection->priv;
3039 node_t *n = channel->node;
3040 meshlink_handle_t *mesh = n->mesh;
3042 if(channel->poll_cb) {
3043 channel->poll_cb(mesh, channel, len);
3047 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3049 channel->poll_cb = cb;
3050 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
3053 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3055 meshlink_errno = MESHLINK_EINVAL;
3059 pthread_mutex_lock(&mesh->mesh_mutex);
3060 mesh->channel_accept_cb = cb;
3061 mesh->receive_cb = channel_receive;
3063 for splay_each(node_t, n, mesh->nodes) {
3064 if(!n->utcp && n != mesh->self) {
3065 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3069 pthread_mutex_unlock(&mesh->mesh_mutex);
3072 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) {
3074 abort(); // TODO: handle non-NULL data
3077 if(!mesh || !node) {
3078 meshlink_errno = MESHLINK_EINVAL;
3082 node_t *n = (node_t *)node;
3085 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3086 mesh->receive_cb = channel_receive;
3089 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3094 if(n->status.blacklisted) {
3095 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3099 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3101 channel->receive_cb = cb;
3102 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3105 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3113 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) {
3114 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3117 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3118 if(!mesh || !channel) {
3119 meshlink_errno = MESHLINK_EINVAL;
3123 utcp_shutdown(channel->c, direction);
3126 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3127 if(!mesh || !channel) {
3128 meshlink_errno = MESHLINK_EINVAL;
3132 utcp_close(channel->c);
3136 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3137 if(!mesh || !channel) {
3138 meshlink_errno = MESHLINK_EINVAL;
3147 meshlink_errno = MESHLINK_EINVAL;
3151 // TODO: more finegrained locking.
3152 // Ideally we want to put the data into the UTCP connection's send buffer.
3153 // Then, preferably only if there is room in the receiver window,
3154 // kick the meshlink thread to go send packets.
3156 pthread_mutex_lock(&mesh->mesh_mutex);
3157 ssize_t retval = utcp_send(channel->c, data, len);
3158 pthread_mutex_unlock(&mesh->mesh_mutex);
3161 meshlink_errno = MESHLINK_ENETWORK;
3167 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3168 if(!mesh || !channel) {
3169 meshlink_errno = MESHLINK_EINVAL;
3173 return channel->c->flags;
3176 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3177 if(!mesh || !channel) {
3178 meshlink_errno = MESHLINK_EINVAL;
3182 return utcp_get_sendq(channel->c);
3185 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3186 if(!mesh || !channel) {
3187 meshlink_errno = MESHLINK_EINVAL;
3191 return utcp_get_recvq(channel->c);
3194 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3195 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3196 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3199 if(mesh->node_status_cb) {
3200 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3204 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3205 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3209 n->status.duplicate = true;
3210 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3213 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3217 meshlink_errno = MESHLINK_EINVAL;
3221 pthread_mutex_lock(&mesh->mesh_mutex);
3223 if(mesh->discovery == enable) {
3227 if(mesh->threadstarted) {
3229 discovery_start(mesh);
3231 discovery_stop(mesh);
3235 mesh->discovery = enable;
3238 pthread_mutex_unlock(&mesh->mesh_mutex);
3242 meshlink_errno = MESHLINK_ENOTSUP;
3246 static void __attribute__((constructor)) meshlink_init(void) {
3249 randomize(&seed, sizeof(seed));
3253 static void __attribute__((destructor)) meshlink_exit(void) {
3257 /// Device class traits
3258 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3259 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3260 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3261 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3262 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN