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"
51 #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 {
219 static void *socket_in_netns_thread(void *arg) {
220 struct socket_in_netns_params *params = arg;
222 if(setns(params->netns, CLONE_NEWNET) == -1) {
223 meshlink_errno = MESHLINK_EINVAL;
227 params->fd = socket(params->domain, params->type, params->protocol);
233 static int socket_in_netns(int domain, int type, int protocol, int netns) {
235 return socket(domain, type, protocol);
239 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
243 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
244 pthread_join(thr, NULL);
254 // Find out what local address a socket would use if we connect to the given address.
255 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
256 // of both endpoints, but this will actually not send any UDP packet.
257 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
258 struct addrinfo *rai = NULL;
259 const struct addrinfo hint = {
260 .ai_family = AF_UNSPEC,
261 .ai_socktype = SOCK_DGRAM,
262 .ai_protocol = IPPROTO_UDP,
265 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
269 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
276 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
284 struct sockaddr_storage sn;
285 socklen_t sl = sizeof(sn);
287 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
294 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
301 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
302 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
305 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
306 char *hostname = NULL;
308 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
309 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
310 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
313 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
314 if(family != AF_UNSPEC && aip->ai_family != family) {
318 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
321 set_timeout(s, 5000);
323 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
330 send(s, request, sizeof(request) - 1, 0);
331 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
336 if(line[len - 1] == '\n') {
340 char *p = strrchr(line, '\n');
343 hostname = xstrdup(p + 1);
359 // Check that the hostname is reasonable
360 if(hostname && !is_valid_hostname(hostname)) {
366 meshlink_errno = MESHLINK_ERESOLV;
372 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
375 // Determine address of the local interface used for outgoing connections.
376 char localaddr[NI_MAXHOST];
377 bool success = false;
379 if(family == AF_INET) {
380 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
381 } else if(family == AF_INET6) {
382 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
386 meshlink_errno = MESHLINK_ENETWORK;
390 return xstrdup(localaddr);
393 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
394 for(int i = 0; i < n; i++) {
399 // Ignore duplicate hostnames
402 for(int j = 0; j < i; j++) {
407 if(strcmp(host[i], host[j])) {
411 if(strcmp(port[i], port[j])) {
429 // This gets the hostname part for use in invitation URLs
430 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
431 char *hostname[4] = {NULL};
432 char *port[4] = {NULL};
433 char *hostport = NULL;
435 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
436 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
439 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
440 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
443 // Add local addresses if requested
444 if(flags & MESHLINK_INVITE_LOCAL) {
445 if(flags & MESHLINK_INVITE_IPV4) {
446 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
449 if(flags & MESHLINK_INVITE_IPV6) {
450 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
454 // Add public/canonical addresses if requested
455 if(flags & MESHLINK_INVITE_PUBLIC) {
456 // Try the CanonicalAddress first
457 char filename[PATH_MAX] = "";
458 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
459 scan_for_canonical_address(filename, &hostname[2], &port[2]);
462 if(flags & MESHLINK_INVITE_IPV4) {
463 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
466 if(flags & MESHLINK_INVITE_IPV6) {
467 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
472 for(int i = 0; i < 4; i++) {
473 // Ensure we always have a port number
474 if(hostname[i] && !port[i]) {
475 port[i] = xstrdup(mesh->myport);
479 remove_duplicate_hostnames(hostname, port, 4);
481 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
482 for(int i = 0; i < 4; i++) {
487 // Convert what we have to a sockaddr
488 struct addrinfo *ai_in, *ai_out;
489 struct addrinfo hint = {
490 .ai_family = AF_UNSPEC,
491 .ai_flags = AI_NUMERICSERV,
492 .ai_socktype = SOCK_STREAM,
494 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
500 // Convert it to a hostname
501 char resolved_host[NI_MAXHOST];
502 char resolved_port[NI_MAXSERV];
503 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
510 // Convert the hostname back to a sockaddr
511 hint.ai_family = ai_in->ai_family;
512 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
519 // Check if it's still the same sockaddr
520 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
522 freeaddrinfo(ai_out);
526 // Yes: replace the hostname with the resolved one
528 hostname[i] = xstrdup(resolved_host);
531 freeaddrinfo(ai_out);
535 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
536 remove_duplicate_hostnames(hostname, port, 4);
538 // Concatenate all unique address to the hostport string
539 for(int i = 0; i < 4; i++) {
544 // Ensure we have the same addresses in our own host config file.
546 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
547 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
550 // Append the address to the hostport string
552 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
554 hostport = newhostport;
563 static char *get_line(const char **data) {
564 if(!data || !*data) {
573 static char line[1024];
574 const char *end = strchr(*data, '\n');
575 size_t len = end ? (size_t)(end - *data) : strlen(*data);
577 if(len >= sizeof(line)) {
578 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
582 if(len && !isprint(**data)) {
586 memcpy(line, *data, len);
598 static char *get_value(const char *data, const char *var) {
599 char *line = get_line(&data);
605 char *sep = line + strcspn(line, " \t=");
606 char *val = sep + strspn(sep, " \t");
609 val += 1 + strspn(val + 1, " \t");
614 if(strcasecmp(line, var)) {
621 static bool try_bind(int port) {
622 struct addrinfo *ai = NULL;
623 struct addrinfo hint = {
624 .ai_flags = AI_PASSIVE,
625 .ai_family = AF_UNSPEC,
626 .ai_socktype = SOCK_STREAM,
627 .ai_protocol = IPPROTO_TCP,
631 snprintf(portstr, sizeof(portstr), "%d", port);
633 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
638 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
639 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
646 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
659 int check_port(meshlink_handle_t *mesh) {
660 for(int i = 0; i < 1000; i++) {
661 int port = 0x1000 + (rand() & 0x7fff);
664 char filename[PATH_MAX];
665 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
666 FILE *f = fopen(filename, "a");
669 meshlink_errno = MESHLINK_ESTORAGE;
670 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
674 fprintf(f, "Port = %d\n", port);
680 meshlink_errno = MESHLINK_ENETWORK;
681 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
685 static void deltree(const char *dirname) {
686 DIR *d = opendir(dirname);
691 while((ent = readdir(d))) {
692 if(ent->d_name[0] == '.') {
696 char filename[PATH_MAX];
697 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
699 if(unlink(filename)) {
710 static bool finalize_join(meshlink_handle_t *mesh) {
711 char *name = xstrdup(get_value(mesh->data, "Name"));
714 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
718 if(!check_id(name)) {
719 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
723 char filename[PATH_MAX];
724 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
726 FILE *f = fopen(filename, "w");
729 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
733 fprintf(f, "Name = %s\n", name);
735 // Wipe all old host config files and invitations
736 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
739 if(mkdir(filename, 0777) && errno != EEXIST) {
740 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
744 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
747 // Create a new host config file for ourself
748 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
749 FILE *fh = fopen(filename, "w");
752 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
757 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
758 // Other chunks go unfiltered to their respective host config files
759 const char *p = mesh->data;
762 while((l = get_line(&p))) {
768 // Split line into variable and value
769 int len = strcspn(l, "\t =");
771 value += strspn(value, "\t ");
775 value += strspn(value, "\t ");
781 if(!strcasecmp(l, "Name"))
782 if(strcmp(value, name)) {
786 } else if(!strcasecmp(l, "NetName")) {
790 // Check the list of known variables
794 for(i = 0; variables[i].name; i++) {
795 if(strcasecmp(l, variables[i].name)) {
803 // Ignore unknown and unsafe variables
805 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
807 } else if(!(variables[i].type & VAR_SAFE)) {
808 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
812 // Copy the safe variable to the right config file
813 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
818 while(l && !strcasecmp(l, "Name")) {
819 if(!check_id(value)) {
820 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
824 if(!strcmp(value, name)) {
825 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
829 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
830 f = fopen(filename, "w");
833 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
837 while((l = get_line(&p))) {
838 if(!strcmp(l, "#---------------------------------------------------------------#")) {
842 int len = strcspn(l, "\t =");
844 if(len == 4 && !strncasecmp(l, "Name", 4)) {
846 value += strspn(value, "\t ");
850 value += strspn(value, "\t ");
864 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
871 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
872 fprintf(fh, "Port = %s\n", mesh->myport);
876 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
880 free(mesh->self->name);
881 free(mesh->self->connection->name);
882 mesh->name = xstrdup(name);
883 mesh->self->name = xstrdup(name);
884 mesh->self->connection->name = name;
886 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
888 load_all_nodes(mesh);
893 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
895 meshlink_handle_t *mesh = handle;
896 const char *ptr = data;
899 int result = send(mesh->sock, ptr, len, 0);
901 if(result == -1 && errno == EINTR) {
903 } else if(result <= 0) {
914 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
915 meshlink_handle_t *mesh = handle;
918 case SPTPS_HANDSHAKE:
919 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
922 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
923 memcpy(mesh->data + mesh->thedatalen, msg, len);
924 mesh->thedatalen += len;
925 mesh->data[mesh->thedatalen] = 0;
929 mesh->thedatalen = 0;
930 return finalize_join(mesh);
933 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
934 shutdown(mesh->sock, SHUT_RDWR);
935 mesh->success = true;
945 static bool recvline(meshlink_handle_t *mesh, size_t len) {
946 char *newline = NULL;
952 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
953 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
955 if(result == -1 && errno == EINTR) {
957 } else if(result <= 0) {
961 mesh->blen += result;
964 if((size_t)(newline - mesh->buffer) >= len) {
968 len = newline - mesh->buffer;
970 memcpy(mesh->line, mesh->buffer, len);
972 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
973 mesh->blen -= len + 1;
977 static bool sendline(int fd, char *format, ...) {
978 static char buffer[4096];
983 va_start(ap, format);
984 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
987 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
995 int result = send(fd, p, blen, MSG_NOSIGNAL);
997 if(result == -1 && errno == EINTR) {
999 } else if(result <= 0) {
1010 static const char *errstr[] = {
1011 [MESHLINK_OK] = "No error",
1012 [MESHLINK_EINVAL] = "Invalid argument",
1013 [MESHLINK_ENOMEM] = "Out of memory",
1014 [MESHLINK_ENOENT] = "No such node",
1015 [MESHLINK_EEXIST] = "Node already exists",
1016 [MESHLINK_EINTERNAL] = "Internal error",
1017 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1018 [MESHLINK_ESTORAGE] = "Storage error",
1019 [MESHLINK_ENETWORK] = "Network error",
1020 [MESHLINK_EPEER] = "Error communicating with peer",
1021 [MESHLINK_ENOTSUP] = "Operation not supported",
1022 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1025 const char *meshlink_strerror(meshlink_errno_t err) {
1026 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1027 return "Invalid error code";
1033 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1036 char pubname[PATH_MAX], privname[PATH_MAX];
1038 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1040 if(!(key = ecdsa_generate())) {
1041 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1042 meshlink_errno = MESHLINK_EINTERNAL;
1045 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1048 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1049 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1050 meshlink_errno = MESHLINK_ESTORAGE;
1054 f = fopen(privname, "wb");
1057 meshlink_errno = MESHLINK_ESTORAGE;
1062 fchmod(fileno(f), 0600);
1065 if(!ecdsa_write_pem_private_key(key, f)) {
1066 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1069 meshlink_errno = MESHLINK_EINTERNAL;
1075 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1076 f = fopen(pubname, "a");
1079 meshlink_errno = MESHLINK_ESTORAGE;
1083 char *pubkey = ecdsa_get_base64_public_key(key);
1084 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1093 static struct timeval idle(event_loop_t *loop, void *data) {
1095 meshlink_handle_t *mesh = data;
1096 struct timeval t, tmin = {3600, 0};
1098 for splay_each(node_t, n, mesh->nodes) {
1103 t = utcp_timeout(n->utcp);
1105 if(timercmp(&t, &tmin, <)) {
1113 // Get our local address(es) by simulating connecting to an Internet host.
1114 static void add_local_addresses(meshlink_handle_t *mesh) {
1115 char host[NI_MAXHOST];
1116 char entry[MAX_STRING_SIZE];
1120 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1121 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1122 append_config_file(mesh, mesh->name, "Address", entry);
1127 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1128 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1129 append_config_file(mesh, mesh->name, "Address", entry);
1133 static bool meshlink_setup(meshlink_handle_t *mesh) {
1134 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1135 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1136 meshlink_errno = MESHLINK_ESTORAGE;
1140 char filename[PATH_MAX];
1141 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1143 if(mkdir(filename, 0777) && errno != EEXIST) {
1144 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1145 meshlink_errno = MESHLINK_ESTORAGE;
1149 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1151 if(!access(filename, F_OK)) {
1152 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1153 meshlink_errno = MESHLINK_EEXIST;
1157 FILE *f = fopen(filename, "w");
1160 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1161 meshlink_errno = MESHLINK_ESTORAGE;
1165 fprintf(f, "Name = %s\n", mesh->name);
1168 if(!ecdsa_keygen(mesh)) {
1169 meshlink_errno = MESHLINK_EINTERNAL;
1174 if(check_port(mesh) == 0) {
1175 meshlink_errno = MESHLINK_ENETWORK;
1184 static void *setup_network_in_netns_thread(void *arg) {
1185 meshlink_handle_t *mesh = arg;
1187 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1191 bool success = setup_network(mesh);
1192 add_local_addresses(mesh);
1193 return success ? arg : NULL;
1195 #endif // HAVE_SETNS
1197 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1198 if(!confbase || !*confbase) {
1199 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1200 meshlink_errno = MESHLINK_EINVAL;
1204 if(!appname || !*appname) {
1205 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1206 meshlink_errno = MESHLINK_EINVAL;
1210 if(strchr(appname, ' ')) {
1211 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1212 meshlink_errno = MESHLINK_EINVAL;
1216 if(!name || !*name) {
1217 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1219 } else { //check name only if there is a name != NULL
1220 if(!check_id(name)) {
1221 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1222 meshlink_errno = MESHLINK_EINVAL;
1227 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1228 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1229 meshlink_errno = MESHLINK_EINVAL;
1233 meshlink_open_params_t *params = xzalloc(sizeof * params);
1235 params->confbase = xstrdup(confbase);
1236 params->name = xstrdup(name);
1237 params->appname = xstrdup(appname);
1238 params->devclass = devclass;
1244 void meshlink_open_params_free(meshlink_open_params_t *params) {
1246 meshlink_errno = MESHLINK_EINVAL;
1250 free(params->confbase);
1252 free(params->appname);
1257 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1258 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1259 meshlink_open_params_t params;
1260 memset(¶ms, 0, sizeof(params));
1262 params.confbase = (char *)confbase;
1263 params.name = (char *)name;
1264 params.appname = (char *)appname;
1265 params.devclass = devclass;
1268 return meshlink_open_ex(¶ms);
1270 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1271 // Validate arguments provided by the application
1272 bool usingname = false;
1274 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1276 if(!params->confbase || !*params->confbase) {
1277 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1278 meshlink_errno = MESHLINK_EINVAL;
1282 if(!params->appname || !*params->appname) {
1283 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1284 meshlink_errno = MESHLINK_EINVAL;
1288 if(strchr(params->appname, ' ')) {
1289 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1290 meshlink_errno = MESHLINK_EINVAL;
1294 if(!params->name || !*params->name) {
1295 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1297 } else { //check name only if there is a name != NULL
1299 if(!check_id(params->name)) {
1300 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1301 meshlink_errno = MESHLINK_EINVAL;
1308 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1309 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1310 meshlink_errno = MESHLINK_EINVAL;
1314 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1315 mesh->confbase = xstrdup(params->confbase);
1316 mesh->appname = xstrdup(params->appname);
1317 mesh->devclass = params->devclass;
1318 mesh->discovery = true;
1319 mesh->invitation_timeout = 604800; // 1 week
1320 mesh->netns = params->netns;
1321 mesh->submeshes = NULL;
1324 mesh->name = xstrdup(params->name);
1328 pthread_mutexattr_t attr;
1329 pthread_mutexattr_init(&attr);
1330 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1331 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1333 mesh->threadstarted = false;
1334 event_loop_init(&mesh->loop);
1335 mesh->loop.data = mesh;
1337 meshlink_queue_init(&mesh->outpacketqueue);
1339 // Check whether meshlink.conf already exists
1341 char filename[PATH_MAX];
1342 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1344 if(access(filename, R_OK)) {
1345 if(errno == ENOENT) {
1346 // If not, create it
1347 if(!meshlink_setup(mesh)) {
1348 // meshlink_errno is set by meshlink_setup()
1352 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1353 meshlink_close(mesh);
1354 meshlink_errno = MESHLINK_ESTORAGE;
1359 // Open the configuration file and lock it
1361 mesh->conffile = fopen(filename, "r");
1363 if(!mesh->conffile) {
1364 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1365 meshlink_close(mesh);
1366 meshlink_errno = MESHLINK_ESTORAGE;
1371 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1375 // TODO: use _locking()?
1378 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1379 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1380 meshlink_close(mesh);
1381 meshlink_errno = MESHLINK_EBUSY;
1387 // Read the configuration
1389 init_configuration(&mesh->config);
1391 if(!read_server_config(mesh)) {
1392 meshlink_close(mesh);
1393 meshlink_errno = MESHLINK_ESTORAGE;
1398 struct WSAData wsa_state;
1400 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1404 // Setup up everything
1405 // TODO: we should not open listening sockets yet
1407 bool success = false;
1409 if(mesh->netns != -1) {
1413 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1414 void *retval = NULL;
1415 success = pthread_join(thr, &retval) == 0 && retval;
1419 meshlink_errno = MESHLINK_EINTERNAL;
1422 #endif // HAVE_SETNS
1424 success = setup_network(mesh);
1425 add_local_addresses(mesh);
1429 meshlink_close(mesh);
1430 meshlink_errno = MESHLINK_ENETWORK;
1434 idle_set(&mesh->loop, idle, mesh);
1436 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1440 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1441 meshlink_submesh_t *s = NULL;
1444 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1445 meshlink_errno = MESHLINK_EINVAL;
1449 if(!submesh || !*submesh) {
1450 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1451 meshlink_errno = MESHLINK_EINVAL;
1456 pthread_mutex_lock(&(mesh->mesh_mutex));
1458 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1460 pthread_mutex_unlock(&(mesh->mesh_mutex));
1465 static void *meshlink_main_loop(void *arg) {
1466 meshlink_handle_t *mesh = arg;
1468 if(mesh->netns != -1) {
1471 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1477 #endif // HAVE_SETNS
1480 pthread_mutex_lock(&(mesh->mesh_mutex));
1482 try_outgoing_connections(mesh);
1484 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1486 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1488 pthread_mutex_unlock(&(mesh->mesh_mutex));
1492 bool meshlink_start(meshlink_handle_t *mesh) {
1494 meshlink_errno = MESHLINK_EINVAL;
1498 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1500 pthread_mutex_lock(&(mesh->mesh_mutex));
1502 if(mesh->threadstarted) {
1503 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1504 pthread_mutex_unlock(&(mesh->mesh_mutex));
1508 if(mesh->listen_socket[0].tcp.fd < 0) {
1509 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1510 meshlink_errno = MESHLINK_ENETWORK;
1514 mesh->thedatalen = 0;
1516 // TODO: open listening sockets first
1518 //Check that a valid name is set
1520 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1521 meshlink_errno = MESHLINK_EINVAL;
1522 pthread_mutex_unlock(&(mesh->mesh_mutex));
1526 // Start the main thread
1528 event_loop_start(&mesh->loop);
1530 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1531 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1532 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1533 meshlink_errno = MESHLINK_EINTERNAL;
1534 event_loop_stop(&mesh->loop);
1535 pthread_mutex_unlock(&(mesh->mesh_mutex));
1539 mesh->threadstarted = true;
1543 if(mesh->discovery) {
1544 discovery_start(mesh);
1549 pthread_mutex_unlock(&(mesh->mesh_mutex));
1553 void meshlink_stop(meshlink_handle_t *mesh) {
1555 meshlink_errno = MESHLINK_EINVAL;
1559 pthread_mutex_lock(&(mesh->mesh_mutex));
1560 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1565 if(mesh->discovery) {
1566 discovery_stop(mesh);
1571 // Shut down the main thread
1572 event_loop_stop(&mesh->loop);
1574 // Send ourselves a UDP packet to kick the event loop
1575 for(int i = 0; i < mesh->listen_sockets; i++) {
1577 socklen_t salen = sizeof(sa.sa);
1579 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1580 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1584 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1585 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1589 if(mesh->threadstarted) {
1590 // Wait for the main thread to finish
1591 pthread_mutex_unlock(&(mesh->mesh_mutex));
1592 pthread_join(mesh->thread, NULL);
1593 pthread_mutex_lock(&(mesh->mesh_mutex));
1595 mesh->threadstarted = false;
1598 // Close all metaconnections
1599 if(mesh->connections) {
1600 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1602 connection_t *c = node->data;
1604 terminate_connection(mesh, c, false);
1608 if(mesh->outgoings) {
1609 list_delete_list(mesh->outgoings);
1610 mesh->outgoings = NULL;
1613 pthread_mutex_unlock(&(mesh->mesh_mutex));
1616 void meshlink_close(meshlink_handle_t *mesh) {
1617 if(!mesh || !mesh->confbase) {
1618 meshlink_errno = MESHLINK_EINVAL;
1622 // stop can be called even if mesh has not been started
1623 meshlink_stop(mesh);
1625 // lock is not released after this
1626 pthread_mutex_lock(&(mesh->mesh_mutex));
1628 // Close and free all resources used.
1630 close_network_connections(mesh);
1632 logger(mesh, MESHLINK_INFO, "Terminating");
1634 exit_configuration(&mesh->config);
1635 event_loop_exit(&mesh->loop);
1639 if(mesh->confbase) {
1645 ecdsa_free(mesh->invitation_key);
1647 if(mesh->netns != -1) {
1652 free(mesh->appname);
1653 free(mesh->confbase);
1654 pthread_mutex_destroy(&(mesh->mesh_mutex));
1656 if(mesh->conffile) {
1657 fclose(mesh->conffile);
1660 memset(mesh, 0, sizeof(*mesh));
1665 bool meshlink_destroy(const char *confbase) {
1667 meshlink_errno = MESHLINK_EINVAL;
1671 char filename[PATH_MAX];
1672 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1674 if(unlink(filename)) {
1675 if(errno == ENOENT) {
1676 meshlink_errno = MESHLINK_ENOENT;
1679 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1680 meshlink_errno = MESHLINK_ESTORAGE;
1690 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1692 meshlink_errno = MESHLINK_EINVAL;
1696 pthread_mutex_lock(&(mesh->mesh_mutex));
1697 mesh->receive_cb = cb;
1698 pthread_mutex_unlock(&(mesh->mesh_mutex));
1701 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1703 meshlink_errno = MESHLINK_EINVAL;
1707 pthread_mutex_lock(&(mesh->mesh_mutex));
1708 mesh->connection_try_cb = cb;
1709 pthread_mutex_unlock(&(mesh->mesh_mutex));
1712 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1714 meshlink_errno = MESHLINK_EINVAL;
1718 pthread_mutex_lock(&(mesh->mesh_mutex));
1719 mesh->node_status_cb = cb;
1720 pthread_mutex_unlock(&(mesh->mesh_mutex));
1723 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1725 meshlink_errno = MESHLINK_EINVAL;
1729 pthread_mutex_lock(&(mesh->mesh_mutex));
1730 mesh->node_duplicate_cb = cb;
1731 pthread_mutex_unlock(&(mesh->mesh_mutex));
1734 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1736 pthread_mutex_lock(&(mesh->mesh_mutex));
1738 mesh->log_level = cb ? level : 0;
1739 pthread_mutex_unlock(&(mesh->mesh_mutex));
1742 global_log_level = cb ? level : 0;
1746 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1747 meshlink_packethdr_t *hdr;
1749 // Validate arguments
1750 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1751 meshlink_errno = MESHLINK_EINVAL;
1760 meshlink_errno = MESHLINK_EINVAL;
1764 node_t *n = (node_t *)destination;
1766 if(n->status.blacklisted) {
1767 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1771 // Prepare the packet
1772 vpn_packet_t *packet = malloc(sizeof(*packet));
1775 meshlink_errno = MESHLINK_ENOMEM;
1779 packet->probe = false;
1780 packet->tcp = false;
1781 packet->len = len + sizeof(*hdr);
1783 hdr = (meshlink_packethdr_t *)packet->data;
1784 memset(hdr, 0, sizeof(*hdr));
1785 // leave the last byte as 0 to make sure strings are always
1786 // null-terminated if they are longer than the buffer
1787 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1788 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1790 memcpy(packet->data + sizeof(*hdr), data, len);
1793 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1795 meshlink_errno = MESHLINK_ENOMEM;
1799 // Notify event loop
1800 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1805 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1807 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1813 mesh->self->in_packets++;
1814 mesh->self->in_bytes += packet->len;
1815 route(mesh, mesh->self, packet);
1818 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1819 if(!mesh || !destination) {
1820 meshlink_errno = MESHLINK_EINVAL;
1824 pthread_mutex_lock(&(mesh->mesh_mutex));
1826 node_t *n = (node_t *)destination;
1828 if(!n->status.reachable) {
1829 pthread_mutex_unlock(&(mesh->mesh_mutex));
1832 } else if(n->mtuprobes > 30 && n->minmtu) {
1833 pthread_mutex_unlock(&(mesh->mesh_mutex));
1836 pthread_mutex_unlock(&(mesh->mesh_mutex));
1841 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1842 if(!mesh || !node) {
1843 meshlink_errno = MESHLINK_EINVAL;
1847 pthread_mutex_lock(&(mesh->mesh_mutex));
1849 node_t *n = (node_t *)node;
1851 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1852 meshlink_errno = MESHLINK_EINTERNAL;
1853 pthread_mutex_unlock(&(mesh->mesh_mutex));
1857 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1860 meshlink_errno = MESHLINK_EINTERNAL;
1863 pthread_mutex_unlock(&(mesh->mesh_mutex));
1867 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1869 meshlink_errno = MESHLINK_EINVAL;
1873 return (meshlink_node_t *)mesh->self;
1876 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1877 if(!mesh || !name) {
1878 meshlink_errno = MESHLINK_EINVAL;
1882 meshlink_node_t *node = NULL;
1884 pthread_mutex_lock(&(mesh->mesh_mutex));
1885 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1886 pthread_mutex_unlock(&(mesh->mesh_mutex));
1890 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1891 if(!mesh || !name) {
1892 meshlink_errno = MESHLINK_EINVAL;
1896 meshlink_submesh_t *submesh = NULL;
1898 pthread_mutex_lock(&(mesh->mesh_mutex));
1899 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1900 pthread_mutex_unlock(&(mesh->mesh_mutex));
1904 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1905 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1906 meshlink_errno = MESHLINK_EINVAL;
1910 meshlink_node_t **result;
1913 pthread_mutex_lock(&(mesh->mesh_mutex));
1915 *nmemb = mesh->nodes->count;
1916 result = realloc(nodes, *nmemb * sizeof(*nodes));
1919 meshlink_node_t **p = result;
1921 for splay_each(node_t, n, mesh->nodes) {
1922 *p++ = (meshlink_node_t *)n;
1927 meshlink_errno = MESHLINK_ENOMEM;
1930 pthread_mutex_unlock(&(mesh->mesh_mutex));
1935 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) {
1936 meshlink_node_t **result;
1938 pthread_mutex_lock(&(mesh->mesh_mutex));
1942 for splay_each(node_t, n, mesh->nodes) {
1943 if(true == search_node(n, condition)) {
1944 *nmemb = *nmemb + 1;
1950 pthread_mutex_unlock(&(mesh->mesh_mutex));
1954 result = realloc(nodes, *nmemb * sizeof(*nodes));
1957 meshlink_node_t **p = result;
1959 for splay_each(node_t, n, mesh->nodes) {
1960 if(true == search_node(n, condition)) {
1961 *p++ = (meshlink_node_t *)n;
1967 meshlink_errno = MESHLINK_ENOMEM;
1970 pthread_mutex_unlock(&(mesh->mesh_mutex));
1975 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1976 dev_class_t *devclass = (dev_class_t *)condition;
1978 if(*devclass == node->devclass) {
1985 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1986 if(condition == node->submesh) {
1993 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) {
1994 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1995 meshlink_errno = MESHLINK_EINVAL;
1999 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2002 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2003 if(!mesh || !submesh || !nmemb) {
2004 meshlink_errno = MESHLINK_EINVAL;
2008 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2011 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2012 if(!mesh || !node) {
2013 meshlink_errno = MESHLINK_EINVAL;
2017 dev_class_t devclass;
2019 pthread_mutex_lock(&(mesh->mesh_mutex));
2021 devclass = ((node_t *)node)->devclass;
2023 pthread_mutex_unlock(&(mesh->mesh_mutex));
2028 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2029 if(!mesh || !node) {
2030 meshlink_errno = MESHLINK_EINVAL;
2034 node_t *n = (node_t *)node;
2036 meshlink_submesh_t *s;
2038 s = (meshlink_submesh_t *)n->submesh;
2043 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2044 if(!mesh || !data || !len || !signature || !siglen) {
2045 meshlink_errno = MESHLINK_EINVAL;
2049 if(*siglen < MESHLINK_SIGLEN) {
2050 meshlink_errno = MESHLINK_EINVAL;
2054 pthread_mutex_lock(&(mesh->mesh_mutex));
2056 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
2057 meshlink_errno = MESHLINK_EINTERNAL;
2058 pthread_mutex_unlock(&(mesh->mesh_mutex));
2062 *siglen = MESHLINK_SIGLEN;
2063 pthread_mutex_unlock(&(mesh->mesh_mutex));
2067 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2068 if(!mesh || !data || !len || !signature) {
2069 meshlink_errno = MESHLINK_EINVAL;
2073 if(siglen != MESHLINK_SIGLEN) {
2074 meshlink_errno = MESHLINK_EINVAL;
2078 pthread_mutex_lock(&(mesh->mesh_mutex));
2082 struct node_t *n = (struct node_t *)source;
2083 node_read_ecdsa_public_key(mesh, n);
2086 meshlink_errno = MESHLINK_EINTERNAL;
2089 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2092 pthread_mutex_unlock(&(mesh->mesh_mutex));
2096 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2097 char filename[PATH_MAX];
2099 pthread_mutex_lock(&(mesh->mesh_mutex));
2101 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2103 if(mkdir(filename, 0700) && errno != EEXIST) {
2104 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2105 meshlink_errno = MESHLINK_ESTORAGE;
2106 pthread_mutex_unlock(&(mesh->mesh_mutex));
2110 // Count the number of valid invitations, clean up old ones
2111 DIR *dir = opendir(filename);
2114 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2115 meshlink_errno = MESHLINK_ESTORAGE;
2116 pthread_mutex_unlock(&(mesh->mesh_mutex));
2123 time_t deadline = time(NULL) - 604800; // 1 week in the past
2125 while((ent = readdir(dir))) {
2126 if(strlen(ent->d_name) != 24) {
2130 char invname[PATH_MAX];
2133 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2134 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2138 if(!stat(invname, &st)) {
2139 if(mesh->invitation_key && deadline < (time_t)st.st_mtime) {
2145 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2151 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2153 meshlink_errno = MESHLINK_ESTORAGE;
2154 pthread_mutex_unlock(&(mesh->mesh_mutex));
2160 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2162 // Remove the key if there are no outstanding invitations.
2166 if(mesh->invitation_key) {
2167 ecdsa_free(mesh->invitation_key);
2168 mesh->invitation_key = NULL;
2172 if(mesh->invitation_key) {
2173 pthread_mutex_unlock(&(mesh->mesh_mutex));
2177 // Create a new key if necessary.
2178 FILE *f = fopen(filename, "rb");
2181 if(errno != ENOENT) {
2182 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2183 meshlink_errno = MESHLINK_ESTORAGE;
2184 pthread_mutex_unlock(&(mesh->mesh_mutex));
2188 mesh->invitation_key = ecdsa_generate();
2190 if(!mesh->invitation_key) {
2191 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2192 meshlink_errno = MESHLINK_EINTERNAL;
2193 pthread_mutex_unlock(&(mesh->mesh_mutex));
2197 f = fopen(filename, "wb");
2200 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2201 meshlink_errno = MESHLINK_ESTORAGE;
2202 pthread_mutex_unlock(&(mesh->mesh_mutex));
2206 chmod(filename, 0600);
2207 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2210 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2213 if(!mesh->invitation_key) {
2214 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2215 meshlink_errno = MESHLINK_ESTORAGE;
2219 pthread_mutex_unlock(&(mesh->mesh_mutex));
2220 return mesh->invitation_key;
2223 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2224 if(!mesh || !node || !address) {
2225 meshlink_errno = MESHLINK_EINVAL;
2229 if(!is_valid_hostname(address)) {
2230 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2231 meshlink_errno = MESHLINK_EINVAL;
2235 if(port && !is_valid_port(port)) {
2236 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2237 meshlink_errno = MESHLINK_EINVAL;
2241 char *canonical_address;
2244 xasprintf(&canonical_address, "%s %s", address, port);
2246 canonical_address = xstrdup(address);
2249 pthread_mutex_lock(&(mesh->mesh_mutex));
2250 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2251 pthread_mutex_unlock(&(mesh->mesh_mutex));
2253 free(canonical_address);
2257 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2258 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2261 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2263 meshlink_errno = MESHLINK_EINVAL;
2267 char *address = meshlink_get_external_address(mesh);
2275 pthread_mutex_lock(&(mesh->mesh_mutex));
2276 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2283 int meshlink_get_port(meshlink_handle_t *mesh) {
2285 meshlink_errno = MESHLINK_EINVAL;
2290 meshlink_errno = MESHLINK_EINTERNAL;
2294 return atoi(mesh->myport);
2297 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2298 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2299 meshlink_errno = MESHLINK_EINVAL;
2303 if(mesh->myport && port == atoi(mesh->myport)) {
2307 if(!try_bind(port)) {
2308 meshlink_errno = MESHLINK_ENETWORK;
2312 devtool_trybind_probe();
2316 pthread_mutex_lock(&(mesh->mesh_mutex));
2318 if(mesh->threadstarted) {
2319 meshlink_errno = MESHLINK_EINVAL;
2323 close_network_connections(mesh);
2324 exit_configuration(&mesh->config);
2327 snprintf(portstr, sizeof(portstr), "%d", port);
2328 portstr[sizeof(portstr) - 1] = 0;
2330 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2332 init_configuration(&mesh->config);
2334 if(!read_server_config(mesh)) {
2335 meshlink_errno = MESHLINK_ESTORAGE;
2336 } else if(!setup_network(mesh)) {
2337 meshlink_errno = MESHLINK_ENETWORK;
2343 pthread_mutex_unlock(&(mesh->mesh_mutex));
2345 return rval && meshlink_get_port(mesh) == port;
2348 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2349 mesh->invitation_timeout = timeout;
2352 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2353 meshlink_submesh_t *s = NULL;
2356 meshlink_errno = MESHLINK_EINVAL;
2361 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2364 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2365 meshlink_errno = MESHLINK_EINVAL;
2369 s = (meshlink_submesh_t *)mesh->self->submesh;
2372 pthread_mutex_lock(&(mesh->mesh_mutex));
2374 // Check validity of the new node's name
2375 if(!check_id(name)) {
2376 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2377 meshlink_errno = MESHLINK_EINVAL;
2378 pthread_mutex_unlock(&(mesh->mesh_mutex));
2382 // Ensure no host configuration file with that name exists
2383 char filename[PATH_MAX];
2384 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2386 if(!access(filename, F_OK)) {
2387 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2388 meshlink_errno = MESHLINK_EEXIST;
2389 pthread_mutex_unlock(&(mesh->mesh_mutex));
2393 // Ensure no other nodes know about this name
2394 if(meshlink_get_node(mesh, name)) {
2395 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2396 meshlink_errno = MESHLINK_EEXIST;
2397 pthread_mutex_unlock(&(mesh->mesh_mutex));
2401 // Get the local address
2402 char *address = get_my_hostname(mesh, flags);
2405 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2406 meshlink_errno = MESHLINK_ERESOLV;
2407 pthread_mutex_unlock(&(mesh->mesh_mutex));
2411 if(!refresh_invitation_key(mesh)) {
2412 meshlink_errno = MESHLINK_EINTERNAL;
2413 pthread_mutex_unlock(&(mesh->mesh_mutex));
2419 // Create a hash of the key.
2420 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2421 sha512(fingerprint, strlen(fingerprint), hash);
2422 b64encode_urlsafe(hash, hash, 18);
2424 // Create a random cookie for this invitation.
2426 randomize(cookie, 18);
2428 // Create a filename that doesn't reveal the cookie itself
2429 char buf[18 + strlen(fingerprint)];
2430 char cookiehash[64];
2431 memcpy(buf, cookie, 18);
2432 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2433 sha512(buf, sizeof(buf), cookiehash);
2434 b64encode_urlsafe(cookiehash, cookiehash, 18);
2436 b64encode_urlsafe(cookie, cookie, 18);
2440 // Create a file containing the details of the invitation.
2441 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2442 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2445 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2446 meshlink_errno = MESHLINK_ESTORAGE;
2447 pthread_mutex_unlock(&(mesh->mesh_mutex));
2451 FILE *f = fdopen(ifd, "w");
2457 // Fill in the details.
2458 fprintf(f, "Name = %s\n", name);
2461 fprintf(f, "SubMesh = %s\n", s->name);
2464 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2466 // Copy Broadcast and Mode
2467 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2468 FILE *tc = fopen(filename, "r");
2473 while(fgets(buf, sizeof(buf), tc)) {
2474 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2475 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2478 // Make sure there is a newline character.
2479 if(!strchr(buf, '\n')) {
2487 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2488 meshlink_errno = MESHLINK_ESTORAGE;
2489 pthread_mutex_unlock(&(mesh->mesh_mutex));
2493 fprintf(f, "#---------------------------------------------------------------#\n");
2494 fprintf(f, "Name = %s\n", mesh->self->name);
2496 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2500 // Create an URL from the local address, key hash and cookie
2502 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2505 pthread_mutex_unlock(&(mesh->mesh_mutex));
2509 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2510 return meshlink_invite_ex(mesh, submesh, name, 0);
2513 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2514 if(!mesh || !invitation) {
2515 meshlink_errno = MESHLINK_EINVAL;
2519 pthread_mutex_lock(&(mesh->mesh_mutex));
2521 //Before doing meshlink_join make sure we are not connected to another mesh
2522 if(mesh->threadstarted) {
2523 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2524 meshlink_errno = MESHLINK_EINVAL;
2525 pthread_mutex_unlock(&(mesh->mesh_mutex));
2529 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2530 char copy[strlen(invitation) + 1];
2531 strcpy(copy, invitation);
2533 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2535 char *slash = strchr(copy, '/');
2543 if(strlen(slash) != 48) {
2547 char *address = copy;
2550 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2554 // Generate a throw-away key for the invitation.
2555 ecdsa_t *key = ecdsa_generate();
2558 meshlink_errno = MESHLINK_EINTERNAL;
2559 pthread_mutex_unlock(&(mesh->mesh_mutex));
2563 char *b64key = ecdsa_get_base64_public_key(key);
2567 while(address && *address) {
2568 // We allow commas in the address part to support multiple addresses in one invitation URL.
2569 comma = strchr(address, ',');
2575 // Split of the port
2576 port = strrchr(address, ':');
2584 // IPv6 address are enclosed in brackets, per RFC 3986
2585 if(*address == '[') {
2587 char *bracket = strchr(address, ']');
2600 // Connect to the meshlink daemon mentioned in the URL.
2601 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2604 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2605 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2607 if(mesh->sock == -1) {
2608 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2609 meshlink_errno = MESHLINK_ENETWORK;
2613 set_timeout(mesh->sock, 5000);
2615 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2616 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2617 meshlink_errno = MESHLINK_ENETWORK;
2618 closesocket(mesh->sock);
2626 meshlink_errno = MESHLINK_ERESOLV;
2629 if(mesh->sock != -1 || !comma) {
2636 if(mesh->sock == -1) {
2637 pthread_mutex_unlock(&mesh->mesh_mutex);
2641 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2643 // Tell him we have an invitation, and give him our throw-away key.
2647 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2648 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2649 closesocket(mesh->sock);
2650 meshlink_errno = MESHLINK_ENETWORK;
2651 pthread_mutex_unlock(&(mesh->mesh_mutex));
2657 char hisname[4096] = "";
2658 int code, hismajor, hisminor = 0;
2660 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) {
2661 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2662 closesocket(mesh->sock);
2663 meshlink_errno = MESHLINK_ENETWORK;
2664 pthread_mutex_unlock(&(mesh->mesh_mutex));
2668 // Check if the hash of the key he gave us matches the hash in the URL.
2669 char *fingerprint = mesh->line + 2;
2672 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2673 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2674 meshlink_errno = MESHLINK_EINTERNAL;
2675 pthread_mutex_unlock(&(mesh->mesh_mutex));
2679 if(memcmp(hishash, mesh->hash, 18)) {
2680 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2681 meshlink_errno = MESHLINK_EPEER;
2682 pthread_mutex_unlock(&(mesh->mesh_mutex));
2687 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2690 meshlink_errno = MESHLINK_EINTERNAL;
2691 pthread_mutex_unlock(&(mesh->mesh_mutex));
2695 // Start an SPTPS session
2696 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2697 meshlink_errno = MESHLINK_EINTERNAL;
2698 pthread_mutex_unlock(&(mesh->mesh_mutex));
2702 // Feed rest of input buffer to SPTPS
2703 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2704 meshlink_errno = MESHLINK_EPEER;
2705 pthread_mutex_unlock(&(mesh->mesh_mutex));
2711 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2713 if(errno == EINTR) {
2717 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2718 meshlink_errno = MESHLINK_ENETWORK;
2719 pthread_mutex_unlock(&(mesh->mesh_mutex));
2723 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2724 meshlink_errno = MESHLINK_EPEER;
2725 pthread_mutex_unlock(&(mesh->mesh_mutex));
2730 sptps_stop(&mesh->sptps);
2733 closesocket(mesh->sock);
2735 if(!mesh->success) {
2736 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2737 meshlink_errno = MESHLINK_EPEER;
2738 pthread_mutex_unlock(&(mesh->mesh_mutex));
2742 pthread_mutex_unlock(&(mesh->mesh_mutex));
2746 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2747 meshlink_errno = MESHLINK_EINVAL;
2748 pthread_mutex_unlock(&(mesh->mesh_mutex));
2752 char *meshlink_export(meshlink_handle_t *mesh) {
2754 meshlink_errno = MESHLINK_EINVAL;
2758 pthread_mutex_lock(&(mesh->mesh_mutex));
2760 char filename[PATH_MAX];
2761 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2762 FILE *f = fopen(filename, "r");
2765 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2766 meshlink_errno = MESHLINK_ESTORAGE;
2767 pthread_mutex_unlock(&(mesh->mesh_mutex));
2771 fseek(f, 0, SEEK_END);
2772 int fsize = ftell(f);
2775 size_t len = fsize + 9 + strlen(mesh->self->name);
2776 char *buf = xmalloc(len);
2777 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2779 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2780 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2783 meshlink_errno = MESHLINK_ESTORAGE;
2784 pthread_mutex_unlock(&(mesh->mesh_mutex));
2791 pthread_mutex_unlock(&(mesh->mesh_mutex));
2795 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2796 if(!mesh || !data) {
2797 meshlink_errno = MESHLINK_EINVAL;
2801 pthread_mutex_lock(&(mesh->mesh_mutex));
2803 if(strncmp(data, "Name = ", 7)) {
2804 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2805 meshlink_errno = MESHLINK_EPEER;
2806 pthread_mutex_unlock(&(mesh->mesh_mutex));
2810 char *end = strchr(data + 7, '\n');
2813 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2814 meshlink_errno = MESHLINK_EPEER;
2815 pthread_mutex_unlock(&(mesh->mesh_mutex));
2819 int len = end - (data + 7);
2821 memcpy(name, data + 7, len);
2824 if(!check_id(name)) {
2825 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2826 meshlink_errno = MESHLINK_EPEER;
2827 pthread_mutex_unlock(&(mesh->mesh_mutex));
2831 char filename[PATH_MAX];
2832 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2834 if(!access(filename, F_OK)) {
2835 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2836 meshlink_errno = MESHLINK_EEXIST;
2837 pthread_mutex_unlock(&(mesh->mesh_mutex));
2841 if(errno != ENOENT) {
2842 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2843 meshlink_errno = MESHLINK_ESTORAGE;
2844 pthread_mutex_unlock(&(mesh->mesh_mutex));
2848 FILE *f = fopen(filename, "w");
2851 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2852 meshlink_errno = MESHLINK_ESTORAGE;
2853 pthread_mutex_unlock(&(mesh->mesh_mutex));
2857 fwrite(end + 1, strlen(end + 1), 1, f);
2860 load_all_nodes(mesh);
2862 pthread_mutex_unlock(&(mesh->mesh_mutex));
2866 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2867 if(!mesh || !node) {
2868 meshlink_errno = MESHLINK_EINVAL;
2872 pthread_mutex_lock(&(mesh->mesh_mutex));
2877 if(n == mesh->self) {
2878 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2879 meshlink_errno = MESHLINK_EINVAL;
2880 pthread_mutex_unlock(&(mesh->mesh_mutex));
2884 if(n->status.blacklisted) {
2885 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2886 pthread_mutex_unlock(&(mesh->mesh_mutex));
2890 n->status.blacklisted = true;
2891 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2893 //Make blacklisting persistent in the config file
2894 append_config_file(mesh, n->name, "blacklisted", "yes");
2896 //Immediately terminate any connections we have with the blacklisted node
2897 for list_each(connection_t, c, mesh->connections) {
2899 terminate_connection(mesh, c, c->status.active);
2903 utcp_abort_all_connections(n->utcp);
2909 n->status.udp_confirmed = false;
2911 if(n->status.reachable) {
2912 update_node_status(mesh, n);
2915 pthread_mutex_unlock(&(mesh->mesh_mutex));
2918 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2919 if(!mesh || !node) {
2920 meshlink_errno = MESHLINK_EINVAL;
2924 pthread_mutex_lock(&(mesh->mesh_mutex));
2926 node_t *n = (node_t *)node;
2928 if(!n->status.blacklisted) {
2929 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2930 meshlink_errno = MESHLINK_EINVAL;
2931 pthread_mutex_unlock(&(mesh->mesh_mutex));
2935 n->status.blacklisted = false;
2937 if(n->status.reachable) {
2938 update_node_status(mesh, n);
2941 //Remove blacklisting from the config file
2942 append_config_file(mesh, n->name, "blacklisted", NULL);
2944 pthread_mutex_unlock(&(mesh->mesh_mutex));
2948 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2949 mesh->default_blacklist = blacklist;
2952 /* Hint that a hostname may be found at an address
2953 * See header file for detailed comment.
2955 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2956 if(!mesh || !node || !addr) {
2960 // Ignore hints about ourself.
2961 if((node_t *)node == mesh->self) {
2965 pthread_mutex_lock(&(mesh->mesh_mutex));
2967 char *host = NULL, *port = NULL, *str = NULL;
2968 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2971 xasprintf(&str, "%s %s", host, port);
2973 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2974 modify_config_file(mesh, node->name, "Address", str, 5);
2976 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2984 pthread_mutex_unlock(&(mesh->mesh_mutex));
2985 // @TODO do we want to fire off a connection attempt right away?
2988 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2990 node_t *n = utcp->priv;
2991 meshlink_handle_t *mesh = n->mesh;
2992 return mesh->channel_accept_cb;
2995 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2996 meshlink_channel_t *channel = connection->priv;
3002 node_t *n = channel->node;
3003 meshlink_handle_t *mesh = n->mesh;
3005 if(n->status.destroyed) {
3006 meshlink_channel_close(mesh, channel);
3007 } else if(channel->receive_cb) {
3008 channel->receive_cb(mesh, channel, data, len);
3014 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3015 node_t *n = utcp_connection->utcp->priv;
3021 meshlink_handle_t *mesh = n->mesh;
3023 if(!mesh->channel_accept_cb) {
3027 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3029 channel->c = utcp_connection;
3031 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3032 utcp_accept(utcp_connection, channel_recv, channel);
3038 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3039 node_t *n = utcp->priv;
3041 if(n->status.destroyed) {
3045 meshlink_handle_t *mesh = n->mesh;
3046 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3049 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3050 if(!mesh || !channel) {
3051 meshlink_errno = MESHLINK_EINVAL;
3055 channel->receive_cb = cb;
3058 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3060 node_t *n = (node_t *)source;
3066 utcp_recv(n->utcp, data, len);
3069 static void channel_poll(struct utcp_connection *connection, size_t len) {
3070 meshlink_channel_t *channel = connection->priv;
3076 node_t *n = channel->node;
3077 meshlink_handle_t *mesh = n->mesh;
3079 if(channel->poll_cb) {
3080 channel->poll_cb(mesh, channel, len);
3084 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3086 channel->poll_cb = cb;
3087 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
3090 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3092 meshlink_errno = MESHLINK_EINVAL;
3096 pthread_mutex_lock(&mesh->mesh_mutex);
3097 mesh->channel_accept_cb = cb;
3098 mesh->receive_cb = channel_receive;
3100 for splay_each(node_t, n, mesh->nodes) {
3101 if(!n->utcp && n != mesh->self) {
3102 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3106 pthread_mutex_unlock(&mesh->mesh_mutex);
3109 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) {
3111 abort(); // TODO: handle non-NULL data
3114 if(!mesh || !node) {
3115 meshlink_errno = MESHLINK_EINVAL;
3119 node_t *n = (node_t *)node;
3122 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3123 mesh->receive_cb = channel_receive;
3126 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3131 if(n->status.blacklisted) {
3132 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3136 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3138 channel->receive_cb = cb;
3139 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3142 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3150 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) {
3151 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3154 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3155 if(!mesh || !channel) {
3156 meshlink_errno = MESHLINK_EINVAL;
3160 utcp_shutdown(channel->c, direction);
3163 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3164 if(!mesh || !channel) {
3165 meshlink_errno = MESHLINK_EINVAL;
3169 utcp_close(channel->c);
3173 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3174 if(!mesh || !channel) {
3175 meshlink_errno = MESHLINK_EINVAL;
3184 meshlink_errno = MESHLINK_EINVAL;
3188 // TODO: more finegrained locking.
3189 // Ideally we want to put the data into the UTCP connection's send buffer.
3190 // Then, preferably only if there is room in the receiver window,
3191 // kick the meshlink thread to go send packets.
3193 pthread_mutex_lock(&mesh->mesh_mutex);
3194 ssize_t retval = utcp_send(channel->c, data, len);
3195 pthread_mutex_unlock(&mesh->mesh_mutex);
3198 meshlink_errno = MESHLINK_ENETWORK;
3204 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3205 if(!mesh || !channel) {
3206 meshlink_errno = MESHLINK_EINVAL;
3210 return channel->c->flags;
3213 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3214 if(!mesh || !channel) {
3215 meshlink_errno = MESHLINK_EINVAL;
3219 return utcp_get_sendq(channel->c);
3222 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3223 if(!mesh || !channel) {
3224 meshlink_errno = MESHLINK_EINVAL;
3228 return utcp_get_recvq(channel->c);
3231 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3232 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3233 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3236 if(mesh->node_status_cb) {
3237 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3241 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3242 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3246 n->status.duplicate = true;
3247 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3250 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3254 meshlink_errno = MESHLINK_EINVAL;
3258 pthread_mutex_lock(&mesh->mesh_mutex);
3260 if(mesh->discovery == enable) {
3264 if(mesh->threadstarted) {
3266 discovery_start(mesh);
3268 discovery_stop(mesh);
3272 mesh->discovery = enable;
3275 pthread_mutex_unlock(&mesh->mesh_mutex);
3279 meshlink_errno = MESHLINK_ENOTSUP;
3283 static void __attribute__((constructor)) meshlink_init(void) {
3286 randomize(&seed, sizeof(seed));
3290 static void __attribute__((destructor)) meshlink_exit(void) {
3294 /// Device class traits
3295 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3296 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3297 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3298 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3299 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN