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 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1851 if(!mesh || !data || !len || !signature || !siglen) {
1852 meshlink_errno = MESHLINK_EINVAL;
1856 if(*siglen < MESHLINK_SIGLEN) {
1857 meshlink_errno = MESHLINK_EINVAL;
1861 pthread_mutex_lock(&(mesh->mesh_mutex));
1863 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1864 meshlink_errno = MESHLINK_EINTERNAL;
1865 pthread_mutex_unlock(&(mesh->mesh_mutex));
1869 *siglen = MESHLINK_SIGLEN;
1870 pthread_mutex_unlock(&(mesh->mesh_mutex));
1874 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1875 if(!mesh || !data || !len || !signature) {
1876 meshlink_errno = MESHLINK_EINVAL;
1880 if(siglen != MESHLINK_SIGLEN) {
1881 meshlink_errno = MESHLINK_EINVAL;
1885 pthread_mutex_lock(&(mesh->mesh_mutex));
1889 struct node_t *n = (struct node_t *)source;
1890 node_read_ecdsa_public_key(mesh, n);
1893 meshlink_errno = MESHLINK_EINTERNAL;
1896 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1899 pthread_mutex_unlock(&(mesh->mesh_mutex));
1903 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1904 char filename[PATH_MAX];
1906 pthread_mutex_lock(&(mesh->mesh_mutex));
1908 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1910 if(mkdir(filename, 0700) && errno != EEXIST) {
1911 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1912 meshlink_errno = MESHLINK_ESTORAGE;
1913 pthread_mutex_unlock(&(mesh->mesh_mutex));
1917 // Count the number of valid invitations, clean up old ones
1918 DIR *dir = opendir(filename);
1921 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1922 meshlink_errno = MESHLINK_ESTORAGE;
1923 pthread_mutex_unlock(&(mesh->mesh_mutex));
1930 time_t deadline = time(NULL) - 604800; // 1 week in the past
1932 while((ent = readdir(dir))) {
1933 if(strlen(ent->d_name) != 24) {
1937 char invname[PATH_MAX];
1940 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1941 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1945 if(!stat(invname, &st)) {
1946 if(mesh->invitation_key && deadline < st.st_mtime) {
1952 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1958 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1960 meshlink_errno = MESHLINK_ESTORAGE;
1961 pthread_mutex_unlock(&(mesh->mesh_mutex));
1967 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1969 // Remove the key if there are no outstanding invitations.
1973 if(mesh->invitation_key) {
1974 ecdsa_free(mesh->invitation_key);
1975 mesh->invitation_key = NULL;
1979 if(mesh->invitation_key) {
1980 pthread_mutex_unlock(&(mesh->mesh_mutex));
1984 // Create a new key if necessary.
1985 FILE *f = fopen(filename, "rb");
1988 if(errno != ENOENT) {
1989 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1990 meshlink_errno = MESHLINK_ESTORAGE;
1991 pthread_mutex_unlock(&(mesh->mesh_mutex));
1995 mesh->invitation_key = ecdsa_generate();
1997 if(!mesh->invitation_key) {
1998 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1999 meshlink_errno = MESHLINK_EINTERNAL;
2000 pthread_mutex_unlock(&(mesh->mesh_mutex));
2004 f = fopen(filename, "wb");
2007 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2008 meshlink_errno = MESHLINK_ESTORAGE;
2009 pthread_mutex_unlock(&(mesh->mesh_mutex));
2013 chmod(filename, 0600);
2014 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2017 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2020 if(!mesh->invitation_key) {
2021 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2022 meshlink_errno = MESHLINK_ESTORAGE;
2026 pthread_mutex_unlock(&(mesh->mesh_mutex));
2027 return mesh->invitation_key;
2030 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2031 if(!mesh || !node || !address) {
2032 meshlink_errno = MESHLINK_EINVAL;
2036 if(!is_valid_hostname(address)) {
2037 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2038 meshlink_errno = MESHLINK_EINVAL;
2042 if(port && !is_valid_port(port)) {
2043 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2044 meshlink_errno = MESHLINK_EINVAL;
2048 char *canonical_address;
2051 xasprintf(&canonical_address, "%s %s", address, port);
2053 canonical_address = xstrdup(address);
2056 pthread_mutex_lock(&(mesh->mesh_mutex));
2057 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2058 pthread_mutex_unlock(&(mesh->mesh_mutex));
2060 free(canonical_address);
2064 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2065 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2068 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2070 meshlink_errno = MESHLINK_EINVAL;
2074 char *address = meshlink_get_external_address(mesh);
2082 pthread_mutex_lock(&(mesh->mesh_mutex));
2083 rval = append_config_file(mesh, mesh->self->name, "Address", address);
2084 pthread_mutex_unlock(&(mesh->mesh_mutex));
2090 int meshlink_get_port(meshlink_handle_t *mesh) {
2092 meshlink_errno = MESHLINK_EINVAL;
2097 meshlink_errno = MESHLINK_EINTERNAL;
2101 return atoi(mesh->myport);
2104 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2105 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2106 meshlink_errno = MESHLINK_EINVAL;
2110 if(mesh->myport && port == atoi(mesh->myport)) {
2114 if(!try_bind(port)) {
2115 meshlink_errno = MESHLINK_ENETWORK;
2121 pthread_mutex_lock(&(mesh->mesh_mutex));
2123 if(mesh->threadstarted) {
2124 meshlink_errno = MESHLINK_EINVAL;
2128 close_network_connections(mesh);
2129 exit_configuration(&mesh->config);
2132 snprintf(portstr, sizeof(portstr), "%d", port);
2133 portstr[sizeof(portstr) - 1] = 0;
2135 modify_config_file(mesh, mesh->name, "Port", portstr, true);
2137 init_configuration(&mesh->config);
2139 if(!read_server_config(mesh)) {
2140 meshlink_errno = MESHLINK_ESTORAGE;
2141 } else if(!setup_network(mesh)) {
2142 meshlink_errno = MESHLINK_ENETWORK;
2148 pthread_mutex_unlock(&(mesh->mesh_mutex));
2153 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2154 mesh->invitation_timeout = timeout;
2157 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
2159 meshlink_errno = MESHLINK_EINVAL;
2163 pthread_mutex_lock(&(mesh->mesh_mutex));
2165 // Check validity of the new node's name
2166 if(!check_id(name)) {
2167 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2168 meshlink_errno = MESHLINK_EINVAL;
2169 pthread_mutex_unlock(&(mesh->mesh_mutex));
2173 // Ensure no host configuration file with that name exists
2174 char filename[PATH_MAX];
2175 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2177 if(!access(filename, F_OK)) {
2178 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2179 meshlink_errno = MESHLINK_EEXIST;
2180 pthread_mutex_unlock(&(mesh->mesh_mutex));
2184 // Ensure no other nodes know about this name
2185 if(meshlink_get_node(mesh, name)) {
2186 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2187 meshlink_errno = MESHLINK_EEXIST;
2188 pthread_mutex_unlock(&(mesh->mesh_mutex));
2192 // Get the local address
2193 char *address = get_my_hostname(mesh, flags);
2196 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2197 meshlink_errno = MESHLINK_ERESOLV;
2198 pthread_mutex_unlock(&(mesh->mesh_mutex));
2202 if(!refresh_invitation_key(mesh)) {
2203 meshlink_errno = MESHLINK_EINTERNAL;
2204 pthread_mutex_unlock(&(mesh->mesh_mutex));
2210 // Create a hash of the key.
2211 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2212 sha512(fingerprint, strlen(fingerprint), hash);
2213 b64encode_urlsafe(hash, hash, 18);
2215 // Create a random cookie for this invitation.
2217 randomize(cookie, 18);
2219 // Create a filename that doesn't reveal the cookie itself
2220 char buf[18 + strlen(fingerprint)];
2221 char cookiehash[64];
2222 memcpy(buf, cookie, 18);
2223 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2224 sha512(buf, sizeof(buf), cookiehash);
2225 b64encode_urlsafe(cookiehash, cookiehash, 18);
2227 b64encode_urlsafe(cookie, cookie, 18);
2231 // Create a file containing the details of the invitation.
2232 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2233 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2236 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2237 meshlink_errno = MESHLINK_ESTORAGE;
2238 pthread_mutex_unlock(&(mesh->mesh_mutex));
2242 FILE *f = fdopen(ifd, "w");
2248 // Fill in the details.
2249 fprintf(f, "Name = %s\n", name);
2250 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2252 // Copy Broadcast and Mode
2253 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2254 FILE *tc = fopen(filename, "r");
2259 while(fgets(buf, sizeof(buf), tc)) {
2260 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2261 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2264 // Make sure there is a newline character.
2265 if(!strchr(buf, '\n')) {
2273 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2274 meshlink_errno = MESHLINK_ESTORAGE;
2275 pthread_mutex_unlock(&(mesh->mesh_mutex));
2279 fprintf(f, "#---------------------------------------------------------------#\n");
2280 fprintf(f, "Name = %s\n", mesh->self->name);
2282 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2286 // Create an URL from the local address, key hash and cookie
2288 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2291 pthread_mutex_unlock(&(mesh->mesh_mutex));
2295 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
2296 return meshlink_invite_ex(mesh, name, 0);
2299 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2300 if(!mesh || !invitation) {
2301 meshlink_errno = MESHLINK_EINVAL;
2305 pthread_mutex_lock(&(mesh->mesh_mutex));
2307 //Before doing meshlink_join make sure we are not connected to another mesh
2308 if(mesh->threadstarted) {
2309 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2310 meshlink_errno = MESHLINK_EINVAL;
2311 pthread_mutex_unlock(&(mesh->mesh_mutex));
2315 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2316 char copy[strlen(invitation) + 1];
2317 strcpy(copy, invitation);
2319 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2321 char *slash = strchr(copy, '/');
2329 if(strlen(slash) != 48) {
2333 char *address = copy;
2336 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2340 // Generate a throw-away key for the invitation.
2341 ecdsa_t *key = ecdsa_generate();
2344 meshlink_errno = MESHLINK_EINTERNAL;
2345 pthread_mutex_unlock(&(mesh->mesh_mutex));
2349 char *b64key = ecdsa_get_base64_public_key(key);
2353 while(address && *address) {
2354 // We allow commas in the address part to support multiple addresses in one invitation URL.
2355 comma = strchr(address, ',');
2361 // Split of the port
2362 port = strrchr(address, ':');
2370 // IPv6 address are enclosed in brackets, per RFC 3986
2371 if(*address == '[') {
2373 char *bracket = strchr(address, ']');
2386 // Connect to the meshlink daemon mentioned in the URL.
2387 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2390 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2391 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2393 if(mesh->sock == -1) {
2394 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2395 meshlink_errno = MESHLINK_ENETWORK;
2399 set_timeout(mesh->sock, 5000);
2401 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2402 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2403 meshlink_errno = MESHLINK_ENETWORK;
2404 closesocket(mesh->sock);
2412 meshlink_errno = MESHLINK_ERESOLV;
2415 if(mesh->sock != -1 || !comma) {
2422 if(mesh->sock == -1) {
2423 pthread_mutex_unlock(&mesh->mesh_mutex);
2427 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2429 // Tell him we have an invitation, and give him our throw-away key.
2433 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2434 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2435 closesocket(mesh->sock);
2436 meshlink_errno = MESHLINK_ENETWORK;
2437 pthread_mutex_unlock(&(mesh->mesh_mutex));
2443 char hisname[4096] = "";
2444 int code, hismajor, hisminor = 0;
2446 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) {
2447 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2448 closesocket(mesh->sock);
2449 meshlink_errno = MESHLINK_ENETWORK;
2450 pthread_mutex_unlock(&(mesh->mesh_mutex));
2454 // Check if the hash of the key he gave us matches the hash in the URL.
2455 char *fingerprint = mesh->line + 2;
2458 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2459 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2460 meshlink_errno = MESHLINK_EINTERNAL;
2461 pthread_mutex_unlock(&(mesh->mesh_mutex));
2465 if(memcmp(hishash, mesh->hash, 18)) {
2466 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2467 meshlink_errno = MESHLINK_EPEER;
2468 pthread_mutex_unlock(&(mesh->mesh_mutex));
2473 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2476 meshlink_errno = MESHLINK_EINTERNAL;
2477 pthread_mutex_unlock(&(mesh->mesh_mutex));
2481 // Start an SPTPS session
2482 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2483 meshlink_errno = MESHLINK_EINTERNAL;
2484 pthread_mutex_unlock(&(mesh->mesh_mutex));
2488 // Feed rest of input buffer to SPTPS
2489 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2490 meshlink_errno = MESHLINK_EPEER;
2491 pthread_mutex_unlock(&(mesh->mesh_mutex));
2497 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2499 if(errno == EINTR) {
2503 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2504 meshlink_errno = MESHLINK_ENETWORK;
2505 pthread_mutex_unlock(&(mesh->mesh_mutex));
2509 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2510 meshlink_errno = MESHLINK_EPEER;
2511 pthread_mutex_unlock(&(mesh->mesh_mutex));
2516 sptps_stop(&mesh->sptps);
2519 closesocket(mesh->sock);
2521 if(!mesh->success) {
2522 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2523 meshlink_errno = MESHLINK_EPEER;
2524 pthread_mutex_unlock(&(mesh->mesh_mutex));
2528 pthread_mutex_unlock(&(mesh->mesh_mutex));
2532 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2533 meshlink_errno = MESHLINK_EINVAL;
2534 pthread_mutex_unlock(&(mesh->mesh_mutex));
2538 char *meshlink_export(meshlink_handle_t *mesh) {
2540 meshlink_errno = MESHLINK_EINVAL;
2544 pthread_mutex_lock(&(mesh->mesh_mutex));
2546 char filename[PATH_MAX];
2547 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2548 FILE *f = fopen(filename, "r");
2551 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2552 meshlink_errno = MESHLINK_ESTORAGE;
2553 pthread_mutex_unlock(&(mesh->mesh_mutex));
2557 fseek(f, 0, SEEK_END);
2558 int fsize = ftell(f);
2561 size_t len = fsize + 9 + strlen(mesh->self->name);
2562 char *buf = xmalloc(len);
2563 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2565 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2566 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2569 meshlink_errno = MESHLINK_ESTORAGE;
2570 pthread_mutex_unlock(&(mesh->mesh_mutex));
2577 pthread_mutex_unlock(&(mesh->mesh_mutex));
2581 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2582 if(!mesh || !data) {
2583 meshlink_errno = MESHLINK_EINVAL;
2587 pthread_mutex_lock(&(mesh->mesh_mutex));
2589 if(strncmp(data, "Name = ", 7)) {
2590 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2591 meshlink_errno = MESHLINK_EPEER;
2592 pthread_mutex_unlock(&(mesh->mesh_mutex));
2596 char *end = strchr(data + 7, '\n');
2599 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2600 meshlink_errno = MESHLINK_EPEER;
2601 pthread_mutex_unlock(&(mesh->mesh_mutex));
2605 int len = end - (data + 7);
2607 memcpy(name, data + 7, len);
2610 if(!check_id(name)) {
2611 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2612 meshlink_errno = MESHLINK_EPEER;
2613 pthread_mutex_unlock(&(mesh->mesh_mutex));
2617 char filename[PATH_MAX];
2618 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2620 if(!access(filename, F_OK)) {
2621 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2622 meshlink_errno = MESHLINK_EEXIST;
2623 pthread_mutex_unlock(&(mesh->mesh_mutex));
2627 if(errno != ENOENT) {
2628 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2629 meshlink_errno = MESHLINK_ESTORAGE;
2630 pthread_mutex_unlock(&(mesh->mesh_mutex));
2634 FILE *f = fopen(filename, "w");
2637 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2638 meshlink_errno = MESHLINK_ESTORAGE;
2639 pthread_mutex_unlock(&(mesh->mesh_mutex));
2643 fwrite(end + 1, strlen(end + 1), 1, f);
2646 load_all_nodes(mesh);
2648 pthread_mutex_unlock(&(mesh->mesh_mutex));
2652 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2653 if(!mesh || !node) {
2654 meshlink_errno = MESHLINK_EINVAL;
2658 pthread_mutex_lock(&(mesh->mesh_mutex));
2662 n->status.blacklisted = true;
2663 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2665 //Make blacklisting persistent in the config file
2666 append_config_file(mesh, n->name, "blacklisted", "yes");
2668 //Immediately terminate any connections we have with the blacklisted node
2669 for list_each(connection_t, c, mesh->connections) {
2671 terminate_connection(mesh, c, c->status.active);
2675 pthread_mutex_unlock(&(mesh->mesh_mutex));
2678 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2679 if(!mesh || !node) {
2680 meshlink_errno = MESHLINK_EINVAL;
2684 pthread_mutex_lock(&(mesh->mesh_mutex));
2686 node_t *n = (node_t *)node;
2687 n->status.blacklisted = false;
2689 //TODO: remove blacklisted = yes from the config file
2691 pthread_mutex_unlock(&(mesh->mesh_mutex));
2695 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2696 mesh->default_blacklist = blacklist;
2699 /* Hint that a hostname may be found at an address
2700 * See header file for detailed comment.
2702 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2703 if(!mesh || !node || !addr) {
2707 // Ignore hints about ourself.
2708 if((node_t *)node == mesh->self) {
2712 pthread_mutex_lock(&(mesh->mesh_mutex));
2714 char *host = NULL, *port = NULL, *str = NULL;
2715 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2718 xasprintf(&str, "%s %s", host, port);
2720 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2721 modify_config_file(mesh, node->name, "Address", str, 5);
2723 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2731 pthread_mutex_unlock(&(mesh->mesh_mutex));
2732 // @TODO do we want to fire off a connection attempt right away?
2735 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2737 node_t *n = utcp->priv;
2738 meshlink_handle_t *mesh = n->mesh;
2739 return mesh->channel_accept_cb;
2742 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2743 meshlink_channel_t *channel = connection->priv;
2749 node_t *n = channel->node;
2750 meshlink_handle_t *mesh = n->mesh;
2752 if(n->status.destroyed) {
2753 meshlink_channel_close(mesh, channel);
2754 } else if(channel->receive_cb) {
2755 channel->receive_cb(mesh, channel, data, len);
2761 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2762 node_t *n = utcp_connection->utcp->priv;
2768 meshlink_handle_t *mesh = n->mesh;
2770 if(!mesh->channel_accept_cb) {
2774 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2776 channel->c = utcp_connection;
2778 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2779 utcp_accept(utcp_connection, channel_recv, channel);
2785 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2786 node_t *n = utcp->priv;
2788 if(n->status.destroyed) {
2792 meshlink_handle_t *mesh = n->mesh;
2793 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2796 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2797 if(!mesh || !channel) {
2798 meshlink_errno = MESHLINK_EINVAL;
2802 channel->receive_cb = cb;
2805 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2807 node_t *n = (node_t *)source;
2813 utcp_recv(n->utcp, data, len);
2816 static void channel_poll(struct utcp_connection *connection, size_t len) {
2817 meshlink_channel_t *channel = connection->priv;
2823 node_t *n = channel->node;
2824 meshlink_handle_t *mesh = n->mesh;
2826 if(channel->poll_cb) {
2827 channel->poll_cb(mesh, channel, len);
2831 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2833 channel->poll_cb = cb;
2834 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2837 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2839 meshlink_errno = MESHLINK_EINVAL;
2843 pthread_mutex_lock(&mesh->mesh_mutex);
2844 mesh->channel_accept_cb = cb;
2845 mesh->receive_cb = channel_receive;
2847 for splay_each(node_t, n, mesh->nodes) {
2848 if(!n->utcp && n != mesh->self) {
2849 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2853 pthread_mutex_unlock(&mesh->mesh_mutex);
2856 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) {
2858 abort(); // TODO: handle non-NULL data
2861 if(!mesh || !node) {
2862 meshlink_errno = MESHLINK_EINVAL;
2866 node_t *n = (node_t *)node;
2869 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2870 mesh->receive_cb = channel_receive;
2873 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2878 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2880 channel->receive_cb = cb;
2881 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2884 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2892 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) {
2893 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2896 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2897 if(!mesh || !channel) {
2898 meshlink_errno = MESHLINK_EINVAL;
2902 utcp_shutdown(channel->c, direction);
2905 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2906 if(!mesh || !channel) {
2907 meshlink_errno = MESHLINK_EINVAL;
2911 utcp_close(channel->c);
2915 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2916 if(!mesh || !channel) {
2917 meshlink_errno = MESHLINK_EINVAL;
2926 meshlink_errno = MESHLINK_EINVAL;
2930 // TODO: more finegrained locking.
2931 // Ideally we want to put the data into the UTCP connection's send buffer.
2932 // Then, preferrably only if there is room in the receiver window,
2933 // kick the meshlink thread to go send packets.
2935 pthread_mutex_lock(&mesh->mesh_mutex);
2936 ssize_t retval = utcp_send(channel->c, data, len);
2937 pthread_mutex_unlock(&mesh->mesh_mutex);
2940 meshlink_errno = MESHLINK_ENETWORK;
2946 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2947 if(!mesh || !channel) {
2948 meshlink_errno = MESHLINK_EINVAL;
2952 return channel->c->flags;
2955 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2956 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2957 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2960 if(mesh->node_status_cb) {
2961 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2965 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2966 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2970 n->status.duplicate = true;
2971 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2974 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2978 meshlink_errno = MESHLINK_EINVAL;
2982 pthread_mutex_lock(&mesh->mesh_mutex);
2984 if(mesh->discovery == enable) {
2988 if(mesh->threadstarted) {
2990 discovery_start(mesh);
2992 discovery_stop(mesh);
2996 mesh->discovery = enable;
2999 pthread_mutex_unlock(&mesh->mesh_mutex);
3003 meshlink_errno = MESHLINK_ENOTSUP;
3007 static void __attribute__((constructor)) meshlink_init(void) {
3010 randomize(&seed, sizeof(seed));
3014 static void __attribute__((destructor)) meshlink_exit(void) {
3018 /// Device class traits
3019 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3020 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3021 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3022 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3023 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN