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"
45 #include "ed25519/sha512.h"
46 #include "discovery.h"
49 #define MSG_NOSIGNAL 0
52 __thread meshlink_errno_t meshlink_errno;
53 meshlink_log_cb_t global_log_cb;
54 meshlink_log_level_t global_log_level;
56 //TODO: this can go away completely
57 const var_t variables[] = {
58 /* Server configuration */
59 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
61 /* Host configuration */
62 {"CanonicalAddress", VAR_HOST},
63 {"Address", VAR_HOST | VAR_MULTIPLE},
64 {"ECDSAPublicKey", VAR_HOST},
69 static bool fcopy(FILE *out, const char *filename) {
70 FILE *in = fopen(filename, "r");
73 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
80 while((len = fread(buf, 1, sizeof(buf), in))) {
81 fwrite(buf, len, 1, out);
88 static int rstrip(char *value) {
89 int len = strlen(value);
91 while(len && strchr("\t\r\n ", value[len - 1])) {
98 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
101 if(!filename || (*hostname && *port)) {
105 FILE *f = fopen(filename, "r");
111 while(fgets(line, sizeof(line), f)) {
117 p += strcspn(p, "\t =");
123 q = p + strspn(p, "\t ");
126 q += 1 + strspn(q + 1, "\t ");
129 // q is now pointing to the hostname
131 p = q + strcspn(q, "\t ");
137 p += strspn(p, "\t ");
138 p[strcspn(p, "\t ")] = 0;
139 // p is now pointing to the port, if present
141 if(!*port && !strcasecmp(line, "Port")) {
143 } else if(!strcasecmp(line, "CanonicalAddress")) {
144 *hostname = xstrdup(q);
152 if(*hostname && *port) {
160 static bool is_valid_hostname(const char *hostname) {
165 for(const char *p = hostname; *p; p++) {
166 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
174 static bool is_valid_port(const char *port) {
181 unsigned long int result = strtoul(port, &end, 10);
182 return result && result < 65536 && !*end;
185 for(const char *p = port; *p; p++) {
186 if(!(isalnum(*p) || *p == '-')) {
194 static void set_timeout(int sock, int timeout) {
199 tv.tv_sec = timeout / 1000;
200 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
202 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
203 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
206 struct socket_in_netns_params {
214 static void *socket_in_netns_thread(void *arg) {
215 struct socket_in_netns_params *params = arg;
217 if(setns(params->netns, CLONE_NEWNET) == -1) {
218 meshlink_errno = MESHLINK_EINVAL;
220 params->fd = socket(params->domain, params->type, params->protocol);
226 static int socket_in_netns(int domain, int type, int protocol, int netns) {
228 return socket(domain, type, protocol);
231 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
235 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
236 pthread_join(thr, NULL);
242 // Find out what local address a socket would use if we connect to the given address.
243 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
244 // of both endpoints, but this will actually not send any UDP packet.
245 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
246 struct addrinfo *rai = NULL;
247 const struct addrinfo hint = {
248 .ai_family = AF_UNSPEC,
249 .ai_socktype = SOCK_DGRAM,
250 .ai_protocol = IPPROTO_UDP,
253 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
257 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
264 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
272 struct sockaddr_storage sn;
273 socklen_t sl = sizeof(sn);
275 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
282 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
289 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
290 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
293 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
294 char *hostname = NULL;
296 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
297 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
298 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
301 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
302 if(family != AF_UNSPEC && aip->ai_family != family) {
306 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
309 set_timeout(s, 5000);
311 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
318 send(s, request, sizeof(request) - 1, 0);
319 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
324 if(line[len - 1] == '\n') {
328 char *p = strrchr(line, '\n');
331 hostname = xstrdup(p + 1);
347 // Check that the hostname is reasonable
348 if(hostname && !is_valid_hostname(hostname)) {
354 meshlink_errno = MESHLINK_ERESOLV;
360 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
363 // Determine address of the local interface used for outgoing connections.
364 char localaddr[NI_MAXHOST];
365 bool success = false;
367 if(family == AF_INET) {
368 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
369 } else if(family == AF_INET6) {
370 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
374 meshlink_errno = MESHLINK_ENETWORK;
378 return xstrdup(localaddr);
381 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
382 for(int i = 0; i < n; i++) {
387 // Ignore duplicate hostnames
390 for(int j = 0; j < i; j++) {
395 if(strcmp(host[i], host[j])) {
399 if(strcmp(port[i], port[j])) {
417 // This gets the hostname part for use in invitation URLs
418 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
419 char *hostname[4] = {NULL};
420 char *port[4] = {NULL};
421 char *hostport = NULL;
423 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
424 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
427 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
428 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
431 // Add local addresses if requested
432 if(flags & MESHLINK_INVITE_LOCAL) {
433 if(flags & MESHLINK_INVITE_IPV4) {
434 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
437 if(flags & MESHLINK_INVITE_IPV6) {
438 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
442 // Add public/canonical addresses if requested
443 if(flags & MESHLINK_INVITE_PUBLIC) {
444 // Try the CanonicalAddress first
445 char filename[PATH_MAX] = "";
446 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
447 scan_for_canonical_address(filename, &hostname[2], &port[2]);
450 if(flags & MESHLINK_INVITE_IPV4) {
451 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
454 if(flags & MESHLINK_INVITE_IPV6) {
455 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
460 for(int i = 0; i < 4; i++) {
461 // Ensure we always have a port number
462 if(hostname[i] && !port[i]) {
463 port[i] = xstrdup(mesh->myport);
467 remove_duplicate_hostnames(hostname, port, 4);
469 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
470 for(int i = 0; i < 4; i++) {
475 // Convert what we have to a sockaddr
476 struct addrinfo *ai_in, *ai_out;
477 struct addrinfo hint = {
478 .ai_family = AF_UNSPEC,
479 .ai_flags = AI_NUMERICSERV,
480 .ai_socktype = SOCK_STREAM,
482 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
488 // Convert it to a hostname
489 char resolved_host[NI_MAXHOST];
490 char resolved_port[NI_MAXSERV];
491 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
498 // Convert the hostname back to a sockaddr
499 hint.ai_family = ai_in->ai_family;
500 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
507 // Check if it's still the same sockaddr
508 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
510 freeaddrinfo(ai_out);
514 // Yes: replace the hostname with the resolved one
516 hostname[i] = xstrdup(resolved_host);
519 freeaddrinfo(ai_out);
523 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
524 remove_duplicate_hostnames(hostname, port, 4);
526 // Concatenate all unique address to the hostport string
527 for(int i = 0; i < 4; i++) {
532 // Ensure we have the same addresses in our own host config file.
534 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
535 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
538 // Append the address to the hostport string
540 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
542 hostport = newhostport;
551 static char *get_line(const char **data) {
552 if(!data || !*data) {
561 static char line[1024];
562 const char *end = strchr(*data, '\n');
563 size_t len = end ? (size_t)(end - *data) : strlen(*data);
565 if(len >= sizeof(line)) {
566 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
570 if(len && !isprint(**data)) {
574 memcpy(line, *data, len);
586 static char *get_value(const char *data, const char *var) {
587 char *line = get_line(&data);
593 char *sep = line + strcspn(line, " \t=");
594 char *val = sep + strspn(sep, " \t");
597 val += 1 + strspn(val + 1, " \t");
602 if(strcasecmp(line, var)) {
609 static bool try_bind(int port) {
610 struct addrinfo *ai = NULL;
611 struct addrinfo hint = {
612 .ai_flags = AI_PASSIVE,
613 .ai_family = AF_UNSPEC,
614 .ai_socktype = SOCK_STREAM,
615 .ai_protocol = IPPROTO_TCP,
619 snprintf(portstr, sizeof(portstr), "%d", port);
621 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
626 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
633 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
648 int check_port(meshlink_handle_t *mesh) {
649 for(int i = 0; i < 1000; i++) {
650 int port = 0x1000 + (rand() & 0x7fff);
653 char filename[PATH_MAX];
654 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
655 FILE *f = fopen(filename, "a");
658 meshlink_errno = MESHLINK_ESTORAGE;
659 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
663 fprintf(f, "Port = %d\n", port);
669 meshlink_errno = MESHLINK_ENETWORK;
670 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
674 static void deltree(const char *dirname) {
675 DIR *d = opendir(dirname);
680 while((ent = readdir(d))) {
681 if(ent->d_name[0] == '.') {
685 char filename[PATH_MAX];
686 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
688 if(unlink(filename)) {
699 static bool finalize_join(meshlink_handle_t *mesh) {
700 char *name = xstrdup(get_value(mesh->data, "Name"));
703 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
707 if(!check_id(name)) {
708 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
712 char filename[PATH_MAX];
713 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
715 FILE *f = fopen(filename, "w");
718 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
722 fprintf(f, "Name = %s\n", name);
724 // Wipe all old host config files and invitations
725 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
728 if(mkdir(filename, 0777) && errno != EEXIST) {
729 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
733 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
736 // Create a new host config file for ourself
737 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
738 FILE *fh = fopen(filename, "w");
741 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
746 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
747 // Other chunks go unfiltered to their respective host config files
748 const char *p = mesh->data;
751 while((l = get_line(&p))) {
757 // Split line into variable and value
758 int len = strcspn(l, "\t =");
760 value += strspn(value, "\t ");
764 value += strspn(value, "\t ");
770 if(!strcasecmp(l, "Name"))
771 if(strcmp(value, name)) {
775 } else if(!strcasecmp(l, "NetName")) {
779 // Check the list of known variables
783 for(i = 0; variables[i].name; i++) {
784 if(strcasecmp(l, variables[i].name)) {
792 // Ignore unknown and unsafe variables
794 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
796 } else if(!(variables[i].type & VAR_SAFE)) {
797 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
801 // Copy the safe variable to the right config file
802 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
807 while(l && !strcasecmp(l, "Name")) {
808 if(!check_id(value)) {
809 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
813 if(!strcmp(value, name)) {
814 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
818 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
819 f = fopen(filename, "w");
822 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
826 while((l = get_line(&p))) {
827 if(!strcmp(l, "#---------------------------------------------------------------#")) {
831 int len = strcspn(l, "\t =");
833 if(len == 4 && !strncasecmp(l, "Name", 4)) {
835 value += strspn(value, "\t ");
839 value += strspn(value, "\t ");
853 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
860 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
861 fprintf(fh, "Port = %s\n", mesh->myport);
865 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
869 free(mesh->self->name);
870 free(mesh->self->connection->name);
871 mesh->name = xstrdup(name);
872 mesh->self->name = xstrdup(name);
873 mesh->self->connection->name = name;
875 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
877 load_all_nodes(mesh);
882 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
884 meshlink_handle_t *mesh = handle;
885 const char *ptr = data;
888 int result = send(mesh->sock, ptr, len, 0);
890 if(result == -1 && errno == EINTR) {
892 } else if(result <= 0) {
903 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
904 meshlink_handle_t *mesh = handle;
907 case SPTPS_HANDSHAKE:
908 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
911 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
912 memcpy(mesh->data + mesh->thedatalen, msg, len);
913 mesh->thedatalen += len;
914 mesh->data[mesh->thedatalen] = 0;
918 mesh->thedatalen = 0;
919 return finalize_join(mesh);
922 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
923 shutdown(mesh->sock, SHUT_RDWR);
924 mesh->success = true;
934 static bool recvline(meshlink_handle_t *mesh, size_t len) {
935 char *newline = NULL;
941 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
942 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
944 if(result == -1 && errno == EINTR) {
946 } else if(result <= 0) {
950 mesh->blen += result;
953 if((size_t)(newline - mesh->buffer) >= len) {
957 len = newline - mesh->buffer;
959 memcpy(mesh->line, mesh->buffer, len);
961 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
962 mesh->blen -= len + 1;
966 static bool sendline(int fd, char *format, ...) {
967 static char buffer[4096];
972 va_start(ap, format);
973 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
976 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
984 int result = send(fd, p, blen, MSG_NOSIGNAL);
986 if(result == -1 && errno == EINTR) {
988 } else if(result <= 0) {
999 static const char *errstr[] = {
1000 [MESHLINK_OK] = "No error",
1001 [MESHLINK_EINVAL] = "Invalid argument",
1002 [MESHLINK_ENOMEM] = "Out of memory",
1003 [MESHLINK_ENOENT] = "No such node",
1004 [MESHLINK_EEXIST] = "Node already exists",
1005 [MESHLINK_EINTERNAL] = "Internal error",
1006 [MESHLINK_ERESOLV] = "Could not resolve hostname",
1007 [MESHLINK_ESTORAGE] = "Storage error",
1008 [MESHLINK_ENETWORK] = "Network error",
1009 [MESHLINK_EPEER] = "Error communicating with peer",
1010 [MESHLINK_ENOTSUP] = "Operation not supported",
1011 [MESHLINK_EBUSY] = "MeshLink instance already in use",
1014 const char *meshlink_strerror(meshlink_errno_t err) {
1015 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1016 return "Invalid error code";
1022 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1025 char pubname[PATH_MAX], privname[PATH_MAX];
1027 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
1029 if(!(key = ecdsa_generate())) {
1030 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
1031 meshlink_errno = MESHLINK_EINTERNAL;
1034 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1037 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1038 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1039 meshlink_errno = MESHLINK_ESTORAGE;
1043 f = fopen(privname, "wb");
1046 meshlink_errno = MESHLINK_ESTORAGE;
1051 fchmod(fileno(f), 0600);
1054 if(!ecdsa_write_pem_private_key(key, f)) {
1055 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1058 meshlink_errno = MESHLINK_EINTERNAL;
1064 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1065 f = fopen(pubname, "a");
1068 meshlink_errno = MESHLINK_ESTORAGE;
1072 char *pubkey = ecdsa_get_base64_public_key(key);
1073 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1082 static struct timeval idle(event_loop_t *loop, void *data) {
1084 meshlink_handle_t *mesh = data;
1085 struct timeval t, tmin = {3600, 0};
1087 for splay_each(node_t, n, mesh->nodes) {
1092 t = utcp_timeout(n->utcp);
1094 if(timercmp(&t, &tmin, <)) {
1102 // Get our local address(es) by simulating connecting to an Internet host.
1103 static void add_local_addresses(meshlink_handle_t *mesh) {
1104 char host[NI_MAXHOST];
1105 char entry[MAX_STRING_SIZE];
1109 if(getlocaladdrname("93.184.216.34", host, sizeof(host), mesh->netns)) {
1110 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1111 append_config_file(mesh, mesh->name, "Address", entry);
1116 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host), mesh->netns)) {
1117 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1118 append_config_file(mesh, mesh->name, "Address", entry);
1122 static bool meshlink_setup(meshlink_handle_t *mesh) {
1123 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1124 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1125 meshlink_errno = MESHLINK_ESTORAGE;
1129 char filename[PATH_MAX];
1130 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1132 if(mkdir(filename, 0777) && errno != EEXIST) {
1133 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1134 meshlink_errno = MESHLINK_ESTORAGE;
1138 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1140 if(!access(filename, F_OK)) {
1141 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1142 meshlink_errno = MESHLINK_EEXIST;
1146 FILE *f = fopen(filename, "w");
1149 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1150 meshlink_errno = MESHLINK_ESTORAGE;
1154 fprintf(f, "Name = %s\n", mesh->name);
1157 if(!ecdsa_keygen(mesh)) {
1158 meshlink_errno = MESHLINK_EINTERNAL;
1163 if(check_port(mesh) == 0) {
1164 meshlink_errno = MESHLINK_ENETWORK;
1172 static void *setup_network_in_netns_thread(void *arg) {
1173 meshlink_handle_t *mesh = arg;
1175 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1179 bool success = setup_network(mesh);
1180 add_local_addresses(mesh);
1181 return success ? arg : NULL;
1184 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1185 if(!confbase || !*confbase) {
1186 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1187 meshlink_errno = MESHLINK_EINVAL;
1191 if(!appname || !*appname) {
1192 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1193 meshlink_errno = MESHLINK_EINVAL;
1197 if(strchr(appname, ' ')) {
1198 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1199 meshlink_errno = MESHLINK_EINVAL;
1203 if(!name || !*name) {
1204 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1206 } else { //check name only if there is a name != NULL
1207 if(!check_id(name)) {
1208 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1209 meshlink_errno = MESHLINK_EINVAL;
1214 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1215 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1216 meshlink_errno = MESHLINK_EINVAL;
1220 meshlink_open_params_t *params = xzalloc(sizeof * params);
1222 params->confbase = xstrdup(confbase);
1223 params->name = xstrdup(name);
1224 params->appname = xstrdup(appname);
1225 params->devclass = devclass;
1231 void meshlink_open_params_free(meshlink_open_params_t *params) {
1233 meshlink_errno = MESHLINK_EINVAL;
1237 free(params->confbase);
1239 free(params->appname);
1244 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1245 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1246 meshlink_open_params_t params = {NULL};
1248 params.confbase = (char *)confbase;
1249 params.name = (char *)name;
1250 params.appname = (char *)appname;
1251 params.devclass = devclass;
1254 return meshlink_open_ex(¶ms);
1256 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1257 // Validate arguments provided by the application
1258 bool usingname = false;
1260 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1262 if(!params->confbase || !*params->confbase) {
1263 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1264 meshlink_errno = MESHLINK_EINVAL;
1268 if(!params->appname || !*params->appname) {
1269 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1270 meshlink_errno = MESHLINK_EINVAL;
1274 if(strchr(params->appname, ' ')) {
1275 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1276 meshlink_errno = MESHLINK_EINVAL;
1280 if(!params->name || !*params->name) {
1281 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1283 } else { //check name only if there is a name != NULL
1285 if(!check_id(params->name)) {
1286 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1287 meshlink_errno = MESHLINK_EINVAL;
1294 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1295 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1296 meshlink_errno = MESHLINK_EINVAL;
1300 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1301 mesh->confbase = xstrdup(params->confbase);
1302 mesh->appname = xstrdup(params->appname);
1303 mesh->devclass = params->devclass;
1304 mesh->discovery = true;
1305 mesh->invitation_timeout = 604800; // 1 week
1306 mesh->netns = params->netns;
1309 mesh->name = xstrdup(params->name);
1313 pthread_mutexattr_t attr;
1314 pthread_mutexattr_init(&attr);
1315 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1316 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1318 mesh->threadstarted = false;
1319 event_loop_init(&mesh->loop);
1320 mesh->loop.data = mesh;
1322 meshlink_queue_init(&mesh->outpacketqueue);
1324 // Check whether meshlink.conf already exists
1326 char filename[PATH_MAX];
1327 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", params->confbase);
1329 if(access(filename, R_OK)) {
1330 if(errno == ENOENT) {
1331 // If not, create it
1332 if(!meshlink_setup(mesh)) {
1333 // meshlink_errno is set by meshlink_setup()
1337 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1338 meshlink_close(mesh);
1339 meshlink_errno = MESHLINK_ESTORAGE;
1344 // Open the configuration file and lock it
1346 mesh->conffile = fopen(filename, "r");
1348 if(!mesh->conffile) {
1349 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1350 meshlink_close(mesh);
1351 meshlink_errno = MESHLINK_ESTORAGE;
1356 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1360 // TODO: use _locking()?
1363 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1364 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1365 meshlink_close(mesh);
1366 meshlink_errno = MESHLINK_EBUSY;
1372 // Read the configuration
1374 init_configuration(&mesh->config);
1376 if(!read_server_config(mesh)) {
1377 meshlink_close(mesh);
1378 meshlink_errno = MESHLINK_ESTORAGE;
1383 struct WSAData wsa_state;
1385 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1389 // Setup up everything
1390 // TODO: we should not open listening sockets yet
1392 bool success = false;
1394 if(mesh->netns != -1) {
1397 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1398 void *retval = NULL;
1399 success = pthread_join(thr, &retval) == 0 && retval;
1402 success = setup_network(mesh);
1403 add_local_addresses(mesh);
1407 meshlink_close(mesh);
1408 meshlink_errno = MESHLINK_ENETWORK;
1412 idle_set(&mesh->loop, idle, mesh);
1414 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1418 static void *meshlink_main_loop(void *arg) {
1419 meshlink_handle_t *mesh = arg;
1421 if(mesh->netns != -1) {
1422 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1427 pthread_mutex_lock(&(mesh->mesh_mutex));
1429 try_outgoing_connections(mesh);
1431 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1433 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1435 pthread_mutex_unlock(&(mesh->mesh_mutex));
1439 bool meshlink_start(meshlink_handle_t *mesh) {
1441 meshlink_errno = MESHLINK_EINVAL;
1445 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1447 pthread_mutex_lock(&(mesh->mesh_mutex));
1449 if(mesh->threadstarted) {
1450 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1451 pthread_mutex_unlock(&(mesh->mesh_mutex));
1455 if(mesh->listen_socket[0].tcp.fd < 0) {
1456 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1457 meshlink_errno = MESHLINK_ENETWORK;
1461 mesh->thedatalen = 0;
1463 // TODO: open listening sockets first
1465 //Check that a valid name is set
1467 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1468 meshlink_errno = MESHLINK_EINVAL;
1469 pthread_mutex_unlock(&(mesh->mesh_mutex));
1473 // Start the main thread
1475 event_loop_start(&mesh->loop);
1477 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1478 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1479 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1480 meshlink_errno = MESHLINK_EINTERNAL;
1481 event_loop_stop(&mesh->loop);
1482 pthread_mutex_unlock(&(mesh->mesh_mutex));
1486 mesh->threadstarted = true;
1490 if(mesh->discovery) {
1491 discovery_start(mesh);
1496 pthread_mutex_unlock(&(mesh->mesh_mutex));
1500 void meshlink_stop(meshlink_handle_t *mesh) {
1502 meshlink_errno = MESHLINK_EINVAL;
1506 pthread_mutex_lock(&(mesh->mesh_mutex));
1507 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1512 if(mesh->discovery) {
1513 discovery_stop(mesh);
1518 // Shut down the main thread
1519 event_loop_stop(&mesh->loop);
1521 // Send ourselves a UDP packet to kick the event loop
1522 for(int i = 0; i < mesh->listen_sockets; i++) {
1524 socklen_t salen = sizeof(sa.sa);
1526 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1527 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1531 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1532 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1536 if(mesh->threadstarted) {
1537 // Wait for the main thread to finish
1538 pthread_mutex_unlock(&(mesh->mesh_mutex));
1539 pthread_join(mesh->thread, NULL);
1540 pthread_mutex_lock(&(mesh->mesh_mutex));
1542 mesh->threadstarted = false;
1545 // Close all metaconnections
1546 if(mesh->connections) {
1547 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1549 connection_t *c = node->data;
1551 terminate_connection(mesh, c, false);
1555 if(mesh->outgoings) {
1556 list_delete_list(mesh->outgoings);
1557 mesh->outgoings = NULL;
1560 pthread_mutex_unlock(&(mesh->mesh_mutex));
1563 void meshlink_close(meshlink_handle_t *mesh) {
1564 if(!mesh || !mesh->confbase) {
1565 meshlink_errno = MESHLINK_EINVAL;
1569 // stop can be called even if mesh has not been started
1570 meshlink_stop(mesh);
1572 // lock is not released after this
1573 pthread_mutex_lock(&(mesh->mesh_mutex));
1575 // Close and free all resources used.
1577 close_network_connections(mesh);
1579 logger(mesh, MESHLINK_INFO, "Terminating");
1581 exit_configuration(&mesh->config);
1582 event_loop_exit(&mesh->loop);
1586 if(mesh->confbase) {
1592 ecdsa_free(mesh->invitation_key);
1594 if(mesh->netns != -1) {
1599 free(mesh->appname);
1600 free(mesh->confbase);
1601 pthread_mutex_destroy(&(mesh->mesh_mutex));
1603 if(mesh->conffile) {
1604 fclose(mesh->conffile);
1607 memset(mesh, 0, sizeof(*mesh));
1612 bool meshlink_destroy(const char *confbase) {
1614 meshlink_errno = MESHLINK_EINVAL;
1618 char filename[PATH_MAX];
1619 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1621 if(unlink(filename)) {
1622 if(errno == ENOENT) {
1623 meshlink_errno = MESHLINK_ENOENT;
1626 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1627 meshlink_errno = MESHLINK_ESTORAGE;
1637 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1639 meshlink_errno = MESHLINK_EINVAL;
1643 pthread_mutex_lock(&(mesh->mesh_mutex));
1644 mesh->receive_cb = cb;
1645 pthread_mutex_unlock(&(mesh->mesh_mutex));
1648 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1650 meshlink_errno = MESHLINK_EINVAL;
1654 pthread_mutex_lock(&(mesh->mesh_mutex));
1655 mesh->node_status_cb = cb;
1656 pthread_mutex_unlock(&(mesh->mesh_mutex));
1659 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1661 meshlink_errno = MESHLINK_EINVAL;
1665 pthread_mutex_lock(&(mesh->mesh_mutex));
1666 mesh->node_duplicate_cb = cb;
1667 pthread_mutex_unlock(&(mesh->mesh_mutex));
1670 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1672 pthread_mutex_lock(&(mesh->mesh_mutex));
1674 mesh->log_level = cb ? level : 0;
1675 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678 global_log_level = cb ? level : 0;
1682 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1683 meshlink_packethdr_t *hdr;
1685 // Validate arguments
1686 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1687 meshlink_errno = MESHLINK_EINVAL;
1696 meshlink_errno = MESHLINK_EINVAL;
1700 // Prepare the packet
1701 vpn_packet_t *packet = malloc(sizeof(*packet));
1704 meshlink_errno = MESHLINK_ENOMEM;
1708 packet->probe = false;
1709 packet->tcp = false;
1710 packet->len = len + sizeof(*hdr);
1712 hdr = (meshlink_packethdr_t *)packet->data;
1713 memset(hdr, 0, sizeof(*hdr));
1714 // leave the last byte as 0 to make sure strings are always
1715 // null-terminated if they are longer than the buffer
1716 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1717 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1719 memcpy(packet->data + sizeof(*hdr), data, len);
1722 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1724 meshlink_errno = MESHLINK_ENOMEM;
1728 // Notify event loop
1729 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1734 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1736 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1742 mesh->self->in_packets++;
1743 mesh->self->in_bytes += packet->len;
1744 route(mesh, mesh->self, packet);
1747 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1748 if(!mesh || !destination) {
1749 meshlink_errno = MESHLINK_EINVAL;
1753 pthread_mutex_lock(&(mesh->mesh_mutex));
1755 node_t *n = (node_t *)destination;
1757 if(!n->status.reachable) {
1758 pthread_mutex_unlock(&(mesh->mesh_mutex));
1761 } else if(n->mtuprobes > 30 && n->minmtu) {
1762 pthread_mutex_unlock(&(mesh->mesh_mutex));
1765 pthread_mutex_unlock(&(mesh->mesh_mutex));
1770 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1771 if(!mesh || !node) {
1772 meshlink_errno = MESHLINK_EINVAL;
1776 pthread_mutex_lock(&(mesh->mesh_mutex));
1778 node_t *n = (node_t *)node;
1780 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1781 meshlink_errno = MESHLINK_EINTERNAL;
1782 pthread_mutex_unlock(&(mesh->mesh_mutex));
1786 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1789 meshlink_errno = MESHLINK_EINTERNAL;
1792 pthread_mutex_unlock(&(mesh->mesh_mutex));
1796 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1798 meshlink_errno = MESHLINK_EINVAL;
1802 return (meshlink_node_t *)mesh->self;
1805 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1806 if(!mesh || !name) {
1807 meshlink_errno = MESHLINK_EINVAL;
1811 meshlink_node_t *node = NULL;
1813 pthread_mutex_lock(&(mesh->mesh_mutex));
1814 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1815 pthread_mutex_unlock(&(mesh->mesh_mutex));
1819 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1820 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1821 meshlink_errno = MESHLINK_EINVAL;
1825 meshlink_node_t **result;
1828 pthread_mutex_lock(&(mesh->mesh_mutex));
1830 *nmemb = mesh->nodes->count;
1831 result = realloc(nodes, *nmemb * sizeof(*nodes));
1834 meshlink_node_t **p = result;
1836 for splay_each(node_t, n, mesh->nodes) {
1837 *p++ = (meshlink_node_t *)n;
1842 meshlink_errno = MESHLINK_ENOMEM;
1845 pthread_mutex_unlock(&(mesh->mesh_mutex));
1850 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) {
1851 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1852 meshlink_errno = MESHLINK_EINVAL;
1856 meshlink_node_t **result;
1858 pthread_mutex_lock(&(mesh->mesh_mutex));
1862 for splay_each(node_t, n, mesh->nodes) {
1863 if(n->devclass == devclass) {
1864 *nmemb = *nmemb + 1;
1870 pthread_mutex_unlock(&(mesh->mesh_mutex));
1874 result = realloc(nodes, *nmemb * sizeof(*nodes));
1877 meshlink_node_t **p = result;
1879 for splay_each(node_t, n, mesh->nodes) {
1880 if(n->devclass == devclass) {
1881 *p++ = (meshlink_node_t *)n;
1887 meshlink_errno = MESHLINK_ENOMEM;
1890 pthread_mutex_unlock(&(mesh->mesh_mutex));
1895 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1896 if(!mesh || !node) {
1897 meshlink_errno = MESHLINK_EINVAL;
1901 dev_class_t devclass;
1903 pthread_mutex_lock(&(mesh->mesh_mutex));
1905 devclass = ((node_t *)node)->devclass;
1907 pthread_mutex_unlock(&(mesh->mesh_mutex));
1912 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1913 if(!mesh || !data || !len || !signature || !siglen) {
1914 meshlink_errno = MESHLINK_EINVAL;
1918 if(*siglen < MESHLINK_SIGLEN) {
1919 meshlink_errno = MESHLINK_EINVAL;
1923 pthread_mutex_lock(&(mesh->mesh_mutex));
1925 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1926 meshlink_errno = MESHLINK_EINTERNAL;
1927 pthread_mutex_unlock(&(mesh->mesh_mutex));
1931 *siglen = MESHLINK_SIGLEN;
1932 pthread_mutex_unlock(&(mesh->mesh_mutex));
1936 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1937 if(!mesh || !data || !len || !signature) {
1938 meshlink_errno = MESHLINK_EINVAL;
1942 if(siglen != MESHLINK_SIGLEN) {
1943 meshlink_errno = MESHLINK_EINVAL;
1947 pthread_mutex_lock(&(mesh->mesh_mutex));
1951 struct node_t *n = (struct node_t *)source;
1952 node_read_ecdsa_public_key(mesh, n);
1955 meshlink_errno = MESHLINK_EINTERNAL;
1958 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1961 pthread_mutex_unlock(&(mesh->mesh_mutex));
1965 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1966 char filename[PATH_MAX];
1968 pthread_mutex_lock(&(mesh->mesh_mutex));
1970 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1972 if(mkdir(filename, 0700) && errno != EEXIST) {
1973 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1974 meshlink_errno = MESHLINK_ESTORAGE;
1975 pthread_mutex_unlock(&(mesh->mesh_mutex));
1979 // Count the number of valid invitations, clean up old ones
1980 DIR *dir = opendir(filename);
1983 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1984 meshlink_errno = MESHLINK_ESTORAGE;
1985 pthread_mutex_unlock(&(mesh->mesh_mutex));
1992 time_t deadline = time(NULL) - 604800; // 1 week in the past
1994 while((ent = readdir(dir))) {
1995 if(strlen(ent->d_name) != 24) {
1999 char invname[PATH_MAX];
2002 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2003 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2007 if(!stat(invname, &st)) {
2008 if(mesh->invitation_key && deadline < st.st_mtime) {
2014 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2020 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2022 meshlink_errno = MESHLINK_ESTORAGE;
2023 pthread_mutex_unlock(&(mesh->mesh_mutex));
2029 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2031 // Remove the key if there are no outstanding invitations.
2035 if(mesh->invitation_key) {
2036 ecdsa_free(mesh->invitation_key);
2037 mesh->invitation_key = NULL;
2041 if(mesh->invitation_key) {
2042 pthread_mutex_unlock(&(mesh->mesh_mutex));
2046 // Create a new key if necessary.
2047 FILE *f = fopen(filename, "rb");
2050 if(errno != ENOENT) {
2051 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2052 meshlink_errno = MESHLINK_ESTORAGE;
2053 pthread_mutex_unlock(&(mesh->mesh_mutex));
2057 mesh->invitation_key = ecdsa_generate();
2059 if(!mesh->invitation_key) {
2060 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2061 meshlink_errno = MESHLINK_EINTERNAL;
2062 pthread_mutex_unlock(&(mesh->mesh_mutex));
2066 f = fopen(filename, "wb");
2069 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2070 meshlink_errno = MESHLINK_ESTORAGE;
2071 pthread_mutex_unlock(&(mesh->mesh_mutex));
2075 chmod(filename, 0600);
2076 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2079 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2082 if(!mesh->invitation_key) {
2083 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2084 meshlink_errno = MESHLINK_ESTORAGE;
2088 pthread_mutex_unlock(&(mesh->mesh_mutex));
2089 return mesh->invitation_key;
2092 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2093 if(!mesh || !node || !address) {
2094 meshlink_errno = MESHLINK_EINVAL;
2098 if(!is_valid_hostname(address)) {
2099 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2100 meshlink_errno = MESHLINK_EINVAL;
2104 if(port && !is_valid_port(port)) {
2105 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2106 meshlink_errno = MESHLINK_EINVAL;
2110 char *canonical_address;
2113 xasprintf(&canonical_address, "%s %s", address, port);
2115 canonical_address = xstrdup(address);
2118 pthread_mutex_lock(&(mesh->mesh_mutex));
2119 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2120 pthread_mutex_unlock(&(mesh->mesh_mutex));
2122 free(canonical_address);
2126 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2127 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2130 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2132 meshlink_errno = MESHLINK_EINVAL;
2136 char *address = meshlink_get_external_address(mesh);
2144 pthread_mutex_lock(&(mesh->mesh_mutex));
2145 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2146 pthread_mutex_unlock(&(mesh->mesh_mutex));
2152 int meshlink_get_port(meshlink_handle_t *mesh) {
2154 meshlink_errno = MESHLINK_EINVAL;
2159 meshlink_errno = MESHLINK_EINTERNAL;
2163 return atoi(mesh->myport);
2166 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2167 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2168 meshlink_errno = MESHLINK_EINVAL;
2172 if(mesh->myport && port == atoi(mesh->myport)) {
2176 if(!try_bind(port)) {
2177 meshlink_errno = MESHLINK_ENETWORK;
2183 pthread_mutex_lock(&(mesh->mesh_mutex));
2185 if(mesh->threadstarted) {
2186 meshlink_errno = MESHLINK_EINVAL;
2190 close_network_connections(mesh);
2191 exit_configuration(&mesh->config);
2194 snprintf(portstr, sizeof(portstr), "%d", port);
2195 portstr[sizeof(portstr) - 1] = 0;
2197 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2199 init_configuration(&mesh->config);
2201 if(!read_server_config(mesh)) {
2202 meshlink_errno = MESHLINK_ESTORAGE;
2203 } else if(!setup_network(mesh)) {
2204 meshlink_errno = MESHLINK_ENETWORK;
2210 pthread_mutex_unlock(&(mesh->mesh_mutex));
2215 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2216 mesh->invitation_timeout = timeout;
2219 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
2221 meshlink_errno = MESHLINK_EINVAL;
2225 pthread_mutex_lock(&(mesh->mesh_mutex));
2227 // Check validity of the new node's name
2228 if(!check_id(name)) {
2229 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2230 meshlink_errno = MESHLINK_EINVAL;
2231 pthread_mutex_unlock(&(mesh->mesh_mutex));
2235 // Ensure no host configuration file with that name exists
2236 char filename[PATH_MAX];
2237 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2239 if(!access(filename, F_OK)) {
2240 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2241 meshlink_errno = MESHLINK_EEXIST;
2242 pthread_mutex_unlock(&(mesh->mesh_mutex));
2246 // Ensure no other nodes know about this name
2247 if(meshlink_get_node(mesh, name)) {
2248 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2249 meshlink_errno = MESHLINK_EEXIST;
2250 pthread_mutex_unlock(&(mesh->mesh_mutex));
2254 // Get the local address
2255 char *address = get_my_hostname(mesh, flags);
2258 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2259 meshlink_errno = MESHLINK_ERESOLV;
2260 pthread_mutex_unlock(&(mesh->mesh_mutex));
2264 if(!refresh_invitation_key(mesh)) {
2265 meshlink_errno = MESHLINK_EINTERNAL;
2266 pthread_mutex_unlock(&(mesh->mesh_mutex));
2272 // Create a hash of the key.
2273 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2274 sha512(fingerprint, strlen(fingerprint), hash);
2275 b64encode_urlsafe(hash, hash, 18);
2277 // Create a random cookie for this invitation.
2279 randomize(cookie, 18);
2281 // Create a filename that doesn't reveal the cookie itself
2282 char buf[18 + strlen(fingerprint)];
2283 char cookiehash[64];
2284 memcpy(buf, cookie, 18);
2285 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2286 sha512(buf, sizeof(buf), cookiehash);
2287 b64encode_urlsafe(cookiehash, cookiehash, 18);
2289 b64encode_urlsafe(cookie, cookie, 18);
2293 // Create a file containing the details of the invitation.
2294 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2295 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2298 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2299 meshlink_errno = MESHLINK_ESTORAGE;
2300 pthread_mutex_unlock(&(mesh->mesh_mutex));
2304 FILE *f = fdopen(ifd, "w");
2310 // Fill in the details.
2311 fprintf(f, "Name = %s\n", name);
2312 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2314 // Copy Broadcast and Mode
2315 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2316 FILE *tc = fopen(filename, "r");
2321 while(fgets(buf, sizeof(buf), tc)) {
2322 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2323 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2326 // Make sure there is a newline character.
2327 if(!strchr(buf, '\n')) {
2335 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2336 meshlink_errno = MESHLINK_ESTORAGE;
2337 pthread_mutex_unlock(&(mesh->mesh_mutex));
2341 fprintf(f, "#---------------------------------------------------------------#\n");
2342 fprintf(f, "Name = %s\n", mesh->self->name);
2344 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2348 // Create an URL from the local address, key hash and cookie
2350 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2353 pthread_mutex_unlock(&(mesh->mesh_mutex));
2357 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
2358 return meshlink_invite_ex(mesh, name, 0);
2361 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2362 if(!mesh || !invitation) {
2363 meshlink_errno = MESHLINK_EINVAL;
2367 pthread_mutex_lock(&(mesh->mesh_mutex));
2369 //Before doing meshlink_join make sure we are not connected to another mesh
2370 if(mesh->threadstarted) {
2371 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2372 meshlink_errno = MESHLINK_EINVAL;
2373 pthread_mutex_unlock(&(mesh->mesh_mutex));
2377 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2378 char copy[strlen(invitation) + 1];
2379 strcpy(copy, invitation);
2381 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2383 char *slash = strchr(copy, '/');
2391 if(strlen(slash) != 48) {
2395 char *address = copy;
2398 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2402 // Generate a throw-away key for the invitation.
2403 ecdsa_t *key = ecdsa_generate();
2406 meshlink_errno = MESHLINK_EINTERNAL;
2407 pthread_mutex_unlock(&(mesh->mesh_mutex));
2411 char *b64key = ecdsa_get_base64_public_key(key);
2415 while(address && *address) {
2416 // We allow commas in the address part to support multiple addresses in one invitation URL.
2417 comma = strchr(address, ',');
2423 // Split of the port
2424 port = strrchr(address, ':');
2432 // IPv6 address are enclosed in brackets, per RFC 3986
2433 if(*address == '[') {
2435 char *bracket = strchr(address, ']');
2448 // Connect to the meshlink daemon mentioned in the URL.
2449 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2452 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2453 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2455 if(mesh->sock == -1) {
2456 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2457 meshlink_errno = MESHLINK_ENETWORK;
2461 set_timeout(mesh->sock, 5000);
2463 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2464 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2465 meshlink_errno = MESHLINK_ENETWORK;
2466 closesocket(mesh->sock);
2474 meshlink_errno = MESHLINK_ERESOLV;
2477 if(mesh->sock != -1 || !comma) {
2484 if(mesh->sock == -1) {
2485 pthread_mutex_unlock(&mesh->mesh_mutex);
2489 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2491 // Tell him we have an invitation, and give him our throw-away key.
2495 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2496 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2497 closesocket(mesh->sock);
2498 meshlink_errno = MESHLINK_ENETWORK;
2499 pthread_mutex_unlock(&(mesh->mesh_mutex));
2505 char hisname[4096] = "";
2506 int code, hismajor, hisminor = 0;
2508 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) {
2509 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2510 closesocket(mesh->sock);
2511 meshlink_errno = MESHLINK_ENETWORK;
2512 pthread_mutex_unlock(&(mesh->mesh_mutex));
2516 // Check if the hash of the key he gave us matches the hash in the URL.
2517 char *fingerprint = mesh->line + 2;
2520 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2521 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2522 meshlink_errno = MESHLINK_EINTERNAL;
2523 pthread_mutex_unlock(&(mesh->mesh_mutex));
2527 if(memcmp(hishash, mesh->hash, 18)) {
2528 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2529 meshlink_errno = MESHLINK_EPEER;
2530 pthread_mutex_unlock(&(mesh->mesh_mutex));
2535 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2538 meshlink_errno = MESHLINK_EINTERNAL;
2539 pthread_mutex_unlock(&(mesh->mesh_mutex));
2543 // Start an SPTPS session
2544 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2545 meshlink_errno = MESHLINK_EINTERNAL;
2546 pthread_mutex_unlock(&(mesh->mesh_mutex));
2550 // Feed rest of input buffer to SPTPS
2551 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2552 meshlink_errno = MESHLINK_EPEER;
2553 pthread_mutex_unlock(&(mesh->mesh_mutex));
2559 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2561 if(errno == EINTR) {
2565 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2566 meshlink_errno = MESHLINK_ENETWORK;
2567 pthread_mutex_unlock(&(mesh->mesh_mutex));
2571 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2572 meshlink_errno = MESHLINK_EPEER;
2573 pthread_mutex_unlock(&(mesh->mesh_mutex));
2578 sptps_stop(&mesh->sptps);
2581 closesocket(mesh->sock);
2583 if(!mesh->success) {
2584 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2585 meshlink_errno = MESHLINK_EPEER;
2586 pthread_mutex_unlock(&(mesh->mesh_mutex));
2590 pthread_mutex_unlock(&(mesh->mesh_mutex));
2594 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2595 meshlink_errno = MESHLINK_EINVAL;
2596 pthread_mutex_unlock(&(mesh->mesh_mutex));
2600 char *meshlink_export(meshlink_handle_t *mesh) {
2602 meshlink_errno = MESHLINK_EINVAL;
2606 pthread_mutex_lock(&(mesh->mesh_mutex));
2608 char filename[PATH_MAX];
2609 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2610 FILE *f = fopen(filename, "r");
2613 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2614 meshlink_errno = MESHLINK_ESTORAGE;
2615 pthread_mutex_unlock(&(mesh->mesh_mutex));
2619 fseek(f, 0, SEEK_END);
2620 int fsize = ftell(f);
2623 size_t len = fsize + 9 + strlen(mesh->self->name);
2624 char *buf = xmalloc(len);
2625 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2627 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2628 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2631 meshlink_errno = MESHLINK_ESTORAGE;
2632 pthread_mutex_unlock(&(mesh->mesh_mutex));
2639 pthread_mutex_unlock(&(mesh->mesh_mutex));
2643 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2644 if(!mesh || !data) {
2645 meshlink_errno = MESHLINK_EINVAL;
2649 pthread_mutex_lock(&(mesh->mesh_mutex));
2651 if(strncmp(data, "Name = ", 7)) {
2652 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2653 meshlink_errno = MESHLINK_EPEER;
2654 pthread_mutex_unlock(&(mesh->mesh_mutex));
2658 char *end = strchr(data + 7, '\n');
2661 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2662 meshlink_errno = MESHLINK_EPEER;
2663 pthread_mutex_unlock(&(mesh->mesh_mutex));
2667 int len = end - (data + 7);
2669 memcpy(name, data + 7, len);
2672 if(!check_id(name)) {
2673 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2674 meshlink_errno = MESHLINK_EPEER;
2675 pthread_mutex_unlock(&(mesh->mesh_mutex));
2679 char filename[PATH_MAX];
2680 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2682 if(!access(filename, F_OK)) {
2683 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2684 meshlink_errno = MESHLINK_EEXIST;
2685 pthread_mutex_unlock(&(mesh->mesh_mutex));
2689 if(errno != ENOENT) {
2690 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2691 meshlink_errno = MESHLINK_ESTORAGE;
2692 pthread_mutex_unlock(&(mesh->mesh_mutex));
2696 FILE *f = fopen(filename, "w");
2699 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2700 meshlink_errno = MESHLINK_ESTORAGE;
2701 pthread_mutex_unlock(&(mesh->mesh_mutex));
2705 fwrite(end + 1, strlen(end + 1), 1, f);
2708 load_all_nodes(mesh);
2710 pthread_mutex_unlock(&(mesh->mesh_mutex));
2714 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2715 if(!mesh || !node) {
2716 meshlink_errno = MESHLINK_EINVAL;
2720 pthread_mutex_lock(&(mesh->mesh_mutex));
2724 n->status.blacklisted = true;
2725 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2727 //Make blacklisting persistent in the config file
2728 append_config_file(mesh, n->name, "blacklisted", "yes");
2730 //Immediately terminate any connections we have with the blacklisted node
2731 for list_each(connection_t, c, mesh->connections) {
2733 terminate_connection(mesh, c, c->status.active);
2737 pthread_mutex_unlock(&(mesh->mesh_mutex));
2740 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2741 if(!mesh || !node) {
2742 meshlink_errno = MESHLINK_EINVAL;
2746 pthread_mutex_lock(&(mesh->mesh_mutex));
2748 node_t *n = (node_t *)node;
2749 n->status.blacklisted = false;
2751 //TODO: remove blacklisted = yes from the config file
2753 pthread_mutex_unlock(&(mesh->mesh_mutex));
2757 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2758 mesh->default_blacklist = blacklist;
2761 /* Hint that a hostname may be found at an address
2762 * See header file for detailed comment.
2764 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2765 if(!mesh || !node || !addr) {
2769 // Ignore hints about ourself.
2770 if((node_t *)node == mesh->self) {
2774 pthread_mutex_lock(&(mesh->mesh_mutex));
2776 char *host = NULL, *port = NULL, *str = NULL;
2777 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2780 xasprintf(&str, "%s %s", host, port);
2782 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2783 modify_config_file(mesh, node->name, "Address", str, 5);
2785 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2793 pthread_mutex_unlock(&(mesh->mesh_mutex));
2794 // @TODO do we want to fire off a connection attempt right away?
2797 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2799 node_t *n = utcp->priv;
2800 meshlink_handle_t *mesh = n->mesh;
2801 return mesh->channel_accept_cb;
2804 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2805 meshlink_channel_t *channel = connection->priv;
2811 node_t *n = channel->node;
2812 meshlink_handle_t *mesh = n->mesh;
2814 if(n->status.destroyed) {
2815 meshlink_channel_close(mesh, channel);
2816 } else if(channel->receive_cb) {
2817 channel->receive_cb(mesh, channel, data, len);
2823 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2824 node_t *n = utcp_connection->utcp->priv;
2830 meshlink_handle_t *mesh = n->mesh;
2832 if(!mesh->channel_accept_cb) {
2836 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2838 channel->c = utcp_connection;
2840 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2841 utcp_accept(utcp_connection, channel_recv, channel);
2847 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2848 node_t *n = utcp->priv;
2850 if(n->status.destroyed) {
2854 meshlink_handle_t *mesh = n->mesh;
2855 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2858 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2859 if(!mesh || !channel) {
2860 meshlink_errno = MESHLINK_EINVAL;
2864 channel->receive_cb = cb;
2867 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2869 node_t *n = (node_t *)source;
2875 utcp_recv(n->utcp, data, len);
2878 static void channel_poll(struct utcp_connection *connection, size_t len) {
2879 meshlink_channel_t *channel = connection->priv;
2885 node_t *n = channel->node;
2886 meshlink_handle_t *mesh = n->mesh;
2888 if(channel->poll_cb) {
2889 channel->poll_cb(mesh, channel, len);
2893 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2895 channel->poll_cb = cb;
2896 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2899 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2901 meshlink_errno = MESHLINK_EINVAL;
2905 pthread_mutex_lock(&mesh->mesh_mutex);
2906 mesh->channel_accept_cb = cb;
2907 mesh->receive_cb = channel_receive;
2909 for splay_each(node_t, n, mesh->nodes) {
2910 if(!n->utcp && n != mesh->self) {
2911 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2915 pthread_mutex_unlock(&mesh->mesh_mutex);
2918 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) {
2920 abort(); // TODO: handle non-NULL data
2923 if(!mesh || !node) {
2924 meshlink_errno = MESHLINK_EINVAL;
2928 node_t *n = (node_t *)node;
2931 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2932 mesh->receive_cb = channel_receive;
2935 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2940 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2942 channel->receive_cb = cb;
2943 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2946 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2954 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) {
2955 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2958 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2959 if(!mesh || !channel) {
2960 meshlink_errno = MESHLINK_EINVAL;
2964 utcp_shutdown(channel->c, direction);
2967 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2968 if(!mesh || !channel) {
2969 meshlink_errno = MESHLINK_EINVAL;
2973 utcp_close(channel->c);
2977 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2978 if(!mesh || !channel) {
2979 meshlink_errno = MESHLINK_EINVAL;
2988 meshlink_errno = MESHLINK_EINVAL;
2992 // TODO: more finegrained locking.
2993 // Ideally we want to put the data into the UTCP connection's send buffer.
2994 // Then, preferrably only if there is room in the receiver window,
2995 // kick the meshlink thread to go send packets.
2997 pthread_mutex_lock(&mesh->mesh_mutex);
2998 ssize_t retval = utcp_send(channel->c, data, len);
2999 pthread_mutex_unlock(&mesh->mesh_mutex);
3002 meshlink_errno = MESHLINK_ENETWORK;
3008 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3009 if(!mesh || !channel) {
3010 meshlink_errno = MESHLINK_EINVAL;
3014 return channel->c->flags;
3017 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3018 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3019 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3022 if(mesh->node_status_cb) {
3023 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
3027 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3028 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3032 n->status.duplicate = true;
3033 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3036 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3040 meshlink_errno = MESHLINK_EINVAL;
3044 pthread_mutex_lock(&mesh->mesh_mutex);
3046 if(mesh->discovery == enable) {
3050 if(mesh->threadstarted) {
3052 discovery_start(mesh);
3054 discovery_stop(mesh);
3058 mesh->discovery = enable;
3061 pthread_mutex_unlock(&mesh->mesh_mutex);
3065 meshlink_errno = MESHLINK_ENOTSUP;
3069 static void __attribute__((constructor)) meshlink_init(void) {
3072 randomize(&seed, sizeof(seed));
3076 static void __attribute__((destructor)) meshlink_exit(void) {
3080 /// Device class traits
3081 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3082 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3083 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3084 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3085 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN