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 // Find out what local address a socket would use if we connect to the given address.
207 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
208 // of both endpoints, but this will actually not send any UDP packet.
209 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
210 struct addrinfo *rai = NULL;
211 const struct addrinfo hint = {
212 .ai_family = AF_UNSPEC,
213 .ai_socktype = SOCK_DGRAM,
214 .ai_protocol = IPPROTO_UDP,
217 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
221 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
228 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
236 struct sockaddr_storage sn;
237 socklen_t sl = sizeof(sn);
239 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
246 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
253 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
254 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
257 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
258 char *hostname = NULL;
260 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
261 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
262 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
265 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
266 if(family != AF_UNSPEC && aip->ai_family != family) {
270 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
273 set_timeout(s, 5000);
275 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
282 send(s, request, sizeof(request) - 1, 0);
283 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
288 if(line[len - 1] == '\n') {
292 char *p = strrchr(line, '\n');
295 hostname = xstrdup(p + 1);
311 // Check that the hostname is reasonable
312 if(hostname && !is_valid_hostname(hostname)) {
318 meshlink_errno = MESHLINK_ERESOLV;
324 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
327 // Determine address of the local interface used for outgoing connections.
328 char localaddr[NI_MAXHOST];
329 bool success = false;
331 if(family == AF_INET) {
332 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
333 } else if(family == AF_INET6) {
334 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
338 meshlink_errno = MESHLINK_ENETWORK;
342 return xstrdup(localaddr);
345 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
346 for(int i = 0; i < n; i++) {
351 // Ignore duplicate hostnames
354 for(int j = 0; j < i; j++) {
359 if(strcmp(host[i], host[j])) {
363 if(strcmp(port[i], port[j])) {
381 // This gets the hostname part for use in invitation URLs
382 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
383 char *hostname[4] = {NULL};
384 char *port[4] = {NULL};
385 char *hostport = NULL;
387 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
388 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
391 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
392 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
395 fprintf(stderr, "flags = %u\n", flags);
397 // Add local addresses if requested
398 if(flags & MESHLINK_INVITE_LOCAL) {
399 if(flags & MESHLINK_INVITE_IPV4) {
400 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
403 if(flags & MESHLINK_INVITE_IPV6) {
404 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
408 // Add public/canonical addresses if requested
409 if(flags & MESHLINK_INVITE_PUBLIC) {
410 // Try the CanonicalAddress first
411 char filename[PATH_MAX] = "";
412 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
413 scan_for_canonical_address(filename, &hostname[2], &port[2]);
416 if(flags & MESHLINK_INVITE_IPV4) {
417 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
420 if(flags & MESHLINK_INVITE_IPV6) {
421 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
426 for(int i = 0; i < 4; i++) {
427 // Ensure we always have a port number
428 if(hostname[i] && !port[i]) {
429 port[i] = xstrdup(mesh->myport);
433 remove_duplicate_hostnames(hostname, port, 4);
435 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
436 for(int i = 0; i < 4; i++) {
441 // Convert what we have to a sockaddr
442 struct addrinfo *ai_in, *ai_out;
443 struct addrinfo hint = {
444 .ai_family = AF_UNSPEC,
445 .ai_flags = AI_NUMERICSERV,
446 .ai_socktype = SOCK_STREAM,
448 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
454 // Convert it to a hostname
455 char resolved_host[NI_MAXHOST];
456 char resolved_port[NI_MAXSERV];
457 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
464 // Convert the hostname back to a sockaddr
465 hint.ai_family = ai_in->ai_family;
466 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
473 // Check if it's still the same sockaddr
474 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
476 freeaddrinfo(ai_out);
480 // Yes: replace the hostname with the resolved one
482 hostname[i] = xstrdup(resolved_host);
485 freeaddrinfo(ai_out);
489 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
490 remove_duplicate_hostnames(hostname, port, 4);
492 // Concatenate all unique address to the hostport string
493 for(int i = 0; i < 4; i++) {
498 // Ensure we have the same addresses in our own host config file.
500 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
501 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
504 // Append the address to the hostport string
506 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
508 hostport = newhostport;
517 static char *get_line(const char **data) {
518 if(!data || !*data) {
527 static char line[1024];
528 const char *end = strchr(*data, '\n');
529 size_t len = end ? (size_t)(end - *data) : strlen(*data);
531 if(len >= sizeof(line)) {
532 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
536 if(len && !isprint(**data)) {
540 memcpy(line, *data, len);
552 static char *get_value(const char *data, const char *var) {
553 char *line = get_line(&data);
559 char *sep = line + strcspn(line, " \t=");
560 char *val = sep + strspn(sep, " \t");
563 val += 1 + strspn(val + 1, " \t");
568 if(strcasecmp(line, var)) {
575 static bool try_bind(int port) {
576 struct addrinfo *ai = NULL;
577 struct addrinfo hint = {
578 .ai_flags = AI_PASSIVE,
579 .ai_family = AF_UNSPEC,
580 .ai_socktype = SOCK_STREAM,
581 .ai_protocol = IPPROTO_TCP,
585 snprintf(portstr, sizeof(portstr), "%d", port);
587 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
592 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
599 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
614 int check_port(meshlink_handle_t *mesh) {
615 for(int i = 0; i < 1000; i++) {
616 int port = 0x1000 + (rand() & 0x7fff);
619 char filename[PATH_MAX];
620 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
621 FILE *f = fopen(filename, "a");
624 meshlink_errno = MESHLINK_ESTORAGE;
625 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
629 fprintf(f, "Port = %d\n", port);
635 meshlink_errno = MESHLINK_ENETWORK;
636 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
640 static void deltree(const char *dirname) {
641 DIR *d = opendir(dirname);
646 while((ent = readdir(d))) {
647 if(ent->d_name[0] == '.') {
651 char filename[PATH_MAX];
652 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
654 if(unlink(filename)) {
665 static bool finalize_join(meshlink_handle_t *mesh) {
666 char *name = xstrdup(get_value(mesh->data, "Name"));
669 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
673 if(!check_id(name)) {
674 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
678 char filename[PATH_MAX];
679 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
681 FILE *f = fopen(filename, "w");
684 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
688 fprintf(f, "Name = %s\n", name);
690 // Wipe all old host config files and invitations
691 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
694 if(mkdir(filename, 0777) && errno != EEXIST) {
695 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
699 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
702 // Create a new host config file for ourself
703 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
704 FILE *fh = fopen(filename, "w");
707 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
712 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
713 // Other chunks go unfiltered to their respective host config files
714 const char *p = mesh->data;
717 while((l = get_line(&p))) {
723 // Split line into variable and value
724 int len = strcspn(l, "\t =");
726 value += strspn(value, "\t ");
730 value += strspn(value, "\t ");
736 if(!strcasecmp(l, "Name"))
737 if(strcmp(value, name)) {
741 } else if(!strcasecmp(l, "NetName")) {
745 // Check the list of known variables
749 for(i = 0; variables[i].name; i++) {
750 if(strcasecmp(l, variables[i].name)) {
758 // Ignore unknown and unsafe variables
760 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
762 } else if(!(variables[i].type & VAR_SAFE)) {
763 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
767 // Copy the safe variable to the right config file
768 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
773 while(l && !strcasecmp(l, "Name")) {
774 if(!check_id(value)) {
775 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
779 if(!strcmp(value, name)) {
780 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
784 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
785 f = fopen(filename, "w");
788 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
792 while((l = get_line(&p))) {
793 if(!strcmp(l, "#---------------------------------------------------------------#")) {
797 int len = strcspn(l, "\t =");
799 if(len == 4 && !strncasecmp(l, "Name", 4)) {
801 value += strspn(value, "\t ");
805 value += strspn(value, "\t ");
819 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
826 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
827 fprintf(fh, "Port = %s\n", mesh->myport);
831 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
835 free(mesh->self->name);
836 free(mesh->self->connection->name);
837 mesh->name = xstrdup(name);
838 mesh->self->name = xstrdup(name);
839 mesh->self->connection->name = name;
841 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
843 load_all_nodes(mesh);
848 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
850 meshlink_handle_t *mesh = handle;
851 const char *ptr = data;
854 int result = send(mesh->sock, ptr, len, 0);
856 if(result == -1 && errno == EINTR) {
858 } else if(result <= 0) {
869 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
870 meshlink_handle_t *mesh = handle;
873 case SPTPS_HANDSHAKE:
874 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
877 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
878 memcpy(mesh->data + mesh->thedatalen, msg, len);
879 mesh->thedatalen += len;
880 mesh->data[mesh->thedatalen] = 0;
884 mesh->thedatalen = 0;
885 return finalize_join(mesh);
888 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
889 shutdown(mesh->sock, SHUT_RDWR);
890 mesh->success = true;
900 static bool recvline(meshlink_handle_t *mesh, size_t len) {
901 char *newline = NULL;
907 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
908 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
910 if(result == -1 && errno == EINTR) {
912 } else if(result <= 0) {
916 mesh->blen += result;
919 if((size_t)(newline - mesh->buffer) >= len) {
923 len = newline - mesh->buffer;
925 memcpy(mesh->line, mesh->buffer, len);
927 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
928 mesh->blen -= len + 1;
932 static bool sendline(int fd, char *format, ...) {
933 static char buffer[4096];
938 va_start(ap, format);
939 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
942 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
950 int result = send(fd, p, blen, MSG_NOSIGNAL);
952 if(result == -1 && errno == EINTR) {
954 } else if(result <= 0) {
965 static const char *errstr[] = {
966 [MESHLINK_OK] = "No error",
967 [MESHLINK_EINVAL] = "Invalid argument",
968 [MESHLINK_ENOMEM] = "Out of memory",
969 [MESHLINK_ENOENT] = "No such node",
970 [MESHLINK_EEXIST] = "Node already exists",
971 [MESHLINK_EINTERNAL] = "Internal error",
972 [MESHLINK_ERESOLV] = "Could not resolve hostname",
973 [MESHLINK_ESTORAGE] = "Storage error",
974 [MESHLINK_ENETWORK] = "Network error",
975 [MESHLINK_EPEER] = "Error communicating with peer",
976 [MESHLINK_ENOTSUP] = "Operation not supported",
977 [MESHLINK_EBUSY] = "MeshLink instance already in use",
980 const char *meshlink_strerror(meshlink_errno_t err) {
981 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
982 return "Invalid error code";
988 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
991 char pubname[PATH_MAX], privname[PATH_MAX];
993 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
995 if(!(key = ecdsa_generate())) {
996 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
997 meshlink_errno = MESHLINK_EINTERNAL;
1000 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1003 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
1004 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1005 meshlink_errno = MESHLINK_ESTORAGE;
1009 f = fopen(privname, "wb");
1012 meshlink_errno = MESHLINK_ESTORAGE;
1017 fchmod(fileno(f), 0600);
1020 if(!ecdsa_write_pem_private_key(key, f)) {
1021 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1024 meshlink_errno = MESHLINK_EINTERNAL;
1030 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1031 f = fopen(pubname, "a");
1034 meshlink_errno = MESHLINK_ESTORAGE;
1038 char *pubkey = ecdsa_get_base64_public_key(key);
1039 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1048 static struct timeval idle(event_loop_t *loop, void *data) {
1050 meshlink_handle_t *mesh = data;
1051 struct timeval t, tmin = {3600, 0};
1053 for splay_each(node_t, n, mesh->nodes) {
1058 t = utcp_timeout(n->utcp);
1060 if(timercmp(&t, &tmin, <)) {
1068 // Get our local address(es) by simulating connecting to an Internet host.
1069 static void add_local_addresses(meshlink_handle_t *mesh) {
1070 char host[NI_MAXHOST];
1071 char entry[MAX_STRING_SIZE];
1075 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
1076 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1077 append_config_file(mesh, mesh->name, "Address", entry);
1082 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
1083 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1084 append_config_file(mesh, mesh->name, "Address", entry);
1088 static bool meshlink_setup(meshlink_handle_t *mesh) {
1089 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1090 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1091 meshlink_errno = MESHLINK_ESTORAGE;
1095 char filename[PATH_MAX];
1096 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1098 if(mkdir(filename, 0777) && errno != EEXIST) {
1099 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1100 meshlink_errno = MESHLINK_ESTORAGE;
1104 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1106 if(!access(filename, F_OK)) {
1107 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1108 meshlink_errno = MESHLINK_EEXIST;
1112 FILE *f = fopen(filename, "w");
1115 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1116 meshlink_errno = MESHLINK_ESTORAGE;
1120 fprintf(f, "Name = %s\n", mesh->name);
1123 if(!ecdsa_keygen(mesh)) {
1124 meshlink_errno = MESHLINK_EINTERNAL;
1129 if(check_port(mesh) == 0) {
1130 meshlink_errno = MESHLINK_ENETWORK;
1138 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1139 // Validate arguments provided by the application
1140 bool usingname = false;
1142 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1144 if(!confbase || !*confbase) {
1145 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1146 meshlink_errno = MESHLINK_EINVAL;
1150 if(!appname || !*appname) {
1151 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1156 if(strchr(appname, ' ')) {
1157 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1158 meshlink_errno = MESHLINK_EINVAL;
1162 if(!name || !*name) {
1163 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1165 } else { //check name only if there is a name != NULL
1167 if(!check_id(name)) {
1168 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1169 meshlink_errno = MESHLINK_EINVAL;
1176 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1177 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1178 meshlink_errno = MESHLINK_EINVAL;
1182 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1183 mesh->confbase = xstrdup(confbase);
1184 mesh->appname = xstrdup(appname);
1185 mesh->devclass = devclass;
1186 mesh->discovery = true;
1187 mesh->invitation_timeout = 604800; // 1 week
1190 mesh->name = xstrdup(name);
1194 pthread_mutexattr_t attr;
1195 pthread_mutexattr_init(&attr);
1196 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1197 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1199 mesh->threadstarted = false;
1200 event_loop_init(&mesh->loop);
1201 mesh->loop.data = mesh;
1203 meshlink_queue_init(&mesh->outpacketqueue);
1205 // Check whether meshlink.conf already exists
1207 char filename[PATH_MAX];
1208 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1210 if(access(filename, R_OK)) {
1211 if(errno == ENOENT) {
1212 // If not, create it
1213 if(!meshlink_setup(mesh)) {
1214 // meshlink_errno is set by meshlink_setup()
1218 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1219 meshlink_close(mesh);
1220 meshlink_errno = MESHLINK_ESTORAGE;
1225 // Open the configuration file and lock it
1227 mesh->conffile = fopen(filename, "r");
1229 if(!mesh->conffile) {
1230 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1231 meshlink_close(mesh);
1232 meshlink_errno = MESHLINK_ESTORAGE;
1237 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1241 // TODO: use _locking()?
1244 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1245 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1246 meshlink_close(mesh);
1247 meshlink_errno = MESHLINK_EBUSY;
1253 // Read the configuration
1255 init_configuration(&mesh->config);
1257 if(!read_server_config(mesh)) {
1258 meshlink_close(mesh);
1259 meshlink_errno = MESHLINK_ESTORAGE;
1264 struct WSAData wsa_state;
1266 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1270 // Setup up everything
1271 // TODO: we should not open listening sockets yet
1273 if(!setup_network(mesh)) {
1274 meshlink_close(mesh);
1275 meshlink_errno = MESHLINK_ENETWORK;
1279 add_local_addresses(mesh);
1281 idle_set(&mesh->loop, idle, mesh);
1283 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1287 static void *meshlink_main_loop(void *arg) {
1288 meshlink_handle_t *mesh = arg;
1290 pthread_mutex_lock(&(mesh->mesh_mutex));
1292 try_outgoing_connections(mesh);
1294 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1296 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1298 pthread_mutex_unlock(&(mesh->mesh_mutex));
1302 bool meshlink_start(meshlink_handle_t *mesh) {
1304 meshlink_errno = MESHLINK_EINVAL;
1308 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1310 pthread_mutex_lock(&(mesh->mesh_mutex));
1312 if(mesh->threadstarted) {
1313 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1314 pthread_mutex_unlock(&(mesh->mesh_mutex));
1318 if(mesh->listen_socket[0].tcp.fd < 0) {
1319 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1320 meshlink_errno = MESHLINK_ENETWORK;
1324 mesh->thedatalen = 0;
1326 // TODO: open listening sockets first
1328 //Check that a valid name is set
1330 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1331 meshlink_errno = MESHLINK_EINVAL;
1332 pthread_mutex_unlock(&(mesh->mesh_mutex));
1336 // Start the main thread
1338 event_loop_start(&mesh->loop);
1340 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1341 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1342 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1343 meshlink_errno = MESHLINK_EINTERNAL;
1344 event_loop_stop(&mesh->loop);
1345 pthread_mutex_unlock(&(mesh->mesh_mutex));
1349 mesh->threadstarted = true;
1353 if(mesh->discovery) {
1354 discovery_start(mesh);
1359 pthread_mutex_unlock(&(mesh->mesh_mutex));
1363 void meshlink_stop(meshlink_handle_t *mesh) {
1365 meshlink_errno = MESHLINK_EINVAL;
1369 pthread_mutex_lock(&(mesh->mesh_mutex));
1370 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1375 if(mesh->discovery) {
1376 discovery_stop(mesh);
1381 // Shut down the main thread
1382 event_loop_stop(&mesh->loop);
1384 // Send ourselves a UDP packet to kick the event loop
1385 for(int i = 0; i < mesh->listen_sockets; i++) {
1387 socklen_t salen = sizeof(sa.sa);
1389 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1390 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1394 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1395 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1399 if(mesh->threadstarted) {
1400 // Wait for the main thread to finish
1401 pthread_mutex_unlock(&(mesh->mesh_mutex));
1402 pthread_join(mesh->thread, NULL);
1403 pthread_mutex_lock(&(mesh->mesh_mutex));
1405 mesh->threadstarted = false;
1408 // Close all metaconnections
1409 if(mesh->connections) {
1410 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1412 connection_t *c = node->data;
1414 terminate_connection(mesh, c, false);
1418 if(mesh->outgoings) {
1419 list_delete_list(mesh->outgoings);
1420 mesh->outgoings = NULL;
1423 pthread_mutex_unlock(&(mesh->mesh_mutex));
1426 void meshlink_close(meshlink_handle_t *mesh) {
1427 if(!mesh || !mesh->confbase) {
1428 meshlink_errno = MESHLINK_EINVAL;
1432 // stop can be called even if mesh has not been started
1433 meshlink_stop(mesh);
1435 // lock is not released after this
1436 pthread_mutex_lock(&(mesh->mesh_mutex));
1438 // Close and free all resources used.
1440 close_network_connections(mesh);
1442 logger(mesh, MESHLINK_INFO, "Terminating");
1444 exit_configuration(&mesh->config);
1445 event_loop_exit(&mesh->loop);
1449 if(mesh->confbase) {
1455 ecdsa_free(mesh->invitation_key);
1458 free(mesh->appname);
1459 free(mesh->confbase);
1460 pthread_mutex_destroy(&(mesh->mesh_mutex));
1462 if(mesh->conffile) {
1463 fclose(mesh->conffile);
1466 memset(mesh, 0, sizeof(*mesh));
1471 bool meshlink_destroy(const char *confbase) {
1473 meshlink_errno = MESHLINK_EINVAL;
1477 char filename[PATH_MAX];
1478 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1480 if(unlink(filename)) {
1481 if(errno == ENOENT) {
1482 meshlink_errno = MESHLINK_ENOENT;
1485 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1486 meshlink_errno = MESHLINK_ESTORAGE;
1496 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1498 meshlink_errno = MESHLINK_EINVAL;
1502 pthread_mutex_lock(&(mesh->mesh_mutex));
1503 mesh->receive_cb = cb;
1504 pthread_mutex_unlock(&(mesh->mesh_mutex));
1507 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1509 meshlink_errno = MESHLINK_EINVAL;
1513 pthread_mutex_lock(&(mesh->mesh_mutex));
1514 mesh->node_status_cb = cb;
1515 pthread_mutex_unlock(&(mesh->mesh_mutex));
1518 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1520 meshlink_errno = MESHLINK_EINVAL;
1524 pthread_mutex_lock(&(mesh->mesh_mutex));
1525 mesh->node_duplicate_cb = cb;
1526 pthread_mutex_unlock(&(mesh->mesh_mutex));
1529 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1531 pthread_mutex_lock(&(mesh->mesh_mutex));
1533 mesh->log_level = cb ? level : 0;
1534 pthread_mutex_unlock(&(mesh->mesh_mutex));
1537 global_log_level = cb ? level : 0;
1541 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1542 meshlink_packethdr_t *hdr;
1544 // Validate arguments
1545 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1546 meshlink_errno = MESHLINK_EINVAL;
1555 meshlink_errno = MESHLINK_EINVAL;
1559 // Prepare the packet
1560 vpn_packet_t *packet = malloc(sizeof(*packet));
1563 meshlink_errno = MESHLINK_ENOMEM;
1567 packet->probe = false;
1568 packet->tcp = false;
1569 packet->len = len + sizeof(*hdr);
1571 hdr = (meshlink_packethdr_t *)packet->data;
1572 memset(hdr, 0, sizeof(*hdr));
1573 // leave the last byte as 0 to make sure strings are always
1574 // null-terminated if they are longer than the buffer
1575 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1576 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1578 memcpy(packet->data + sizeof(*hdr), data, len);
1581 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1583 meshlink_errno = MESHLINK_ENOMEM;
1587 // Notify event loop
1588 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1593 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1595 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1601 mesh->self->in_packets++;
1602 mesh->self->in_bytes += packet->len;
1603 route(mesh, mesh->self, packet);
1606 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1607 if(!mesh || !destination) {
1608 meshlink_errno = MESHLINK_EINVAL;
1612 pthread_mutex_lock(&(mesh->mesh_mutex));
1614 node_t *n = (node_t *)destination;
1616 if(!n->status.reachable) {
1617 pthread_mutex_unlock(&(mesh->mesh_mutex));
1620 } else if(n->mtuprobes > 30 && n->minmtu) {
1621 pthread_mutex_unlock(&(mesh->mesh_mutex));
1624 pthread_mutex_unlock(&(mesh->mesh_mutex));
1629 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1630 if(!mesh || !node) {
1631 meshlink_errno = MESHLINK_EINVAL;
1635 pthread_mutex_lock(&(mesh->mesh_mutex));
1637 node_t *n = (node_t *)node;
1639 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1640 meshlink_errno = MESHLINK_EINTERNAL;
1641 pthread_mutex_unlock(&(mesh->mesh_mutex));
1645 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1648 meshlink_errno = MESHLINK_EINTERNAL;
1651 pthread_mutex_unlock(&(mesh->mesh_mutex));
1655 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1657 meshlink_errno = MESHLINK_EINVAL;
1661 return (meshlink_node_t *)mesh->self;
1664 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1665 if(!mesh || !name) {
1666 meshlink_errno = MESHLINK_EINVAL;
1670 meshlink_node_t *node = NULL;
1672 pthread_mutex_lock(&(mesh->mesh_mutex));
1673 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1674 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1679 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1680 meshlink_errno = MESHLINK_EINVAL;
1684 meshlink_node_t **result;
1687 pthread_mutex_lock(&(mesh->mesh_mutex));
1689 *nmemb = mesh->nodes->count;
1690 result = realloc(nodes, *nmemb * sizeof(*nodes));
1693 meshlink_node_t **p = result;
1695 for splay_each(node_t, n, mesh->nodes) {
1696 *p++ = (meshlink_node_t *)n;
1701 meshlink_errno = MESHLINK_ENOMEM;
1704 pthread_mutex_unlock(&(mesh->mesh_mutex));
1709 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1710 if(!mesh || !data || !len || !signature || !siglen) {
1711 meshlink_errno = MESHLINK_EINVAL;
1715 if(*siglen < MESHLINK_SIGLEN) {
1716 meshlink_errno = MESHLINK_EINVAL;
1720 pthread_mutex_lock(&(mesh->mesh_mutex));
1722 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1723 meshlink_errno = MESHLINK_EINTERNAL;
1724 pthread_mutex_unlock(&(mesh->mesh_mutex));
1728 *siglen = MESHLINK_SIGLEN;
1729 pthread_mutex_unlock(&(mesh->mesh_mutex));
1733 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1734 if(!mesh || !data || !len || !signature) {
1735 meshlink_errno = MESHLINK_EINVAL;
1739 if(siglen != MESHLINK_SIGLEN) {
1740 meshlink_errno = MESHLINK_EINVAL;
1744 pthread_mutex_lock(&(mesh->mesh_mutex));
1748 struct node_t *n = (struct node_t *)source;
1749 node_read_ecdsa_public_key(mesh, n);
1752 meshlink_errno = MESHLINK_EINTERNAL;
1755 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1758 pthread_mutex_unlock(&(mesh->mesh_mutex));
1762 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1763 char filename[PATH_MAX];
1765 pthread_mutex_lock(&(mesh->mesh_mutex));
1767 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1769 if(mkdir(filename, 0700) && errno != EEXIST) {
1770 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1771 meshlink_errno = MESHLINK_ESTORAGE;
1772 pthread_mutex_unlock(&(mesh->mesh_mutex));
1776 // Count the number of valid invitations, clean up old ones
1777 DIR *dir = opendir(filename);
1780 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1781 meshlink_errno = MESHLINK_ESTORAGE;
1782 pthread_mutex_unlock(&(mesh->mesh_mutex));
1789 time_t deadline = time(NULL) - 604800; // 1 week in the past
1791 while((ent = readdir(dir))) {
1792 if(strlen(ent->d_name) != 24) {
1796 char invname[PATH_MAX];
1799 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1800 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1804 if(!stat(invname, &st)) {
1805 if(mesh->invitation_key && deadline < st.st_mtime) {
1811 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1817 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1819 meshlink_errno = MESHLINK_ESTORAGE;
1820 pthread_mutex_unlock(&(mesh->mesh_mutex));
1826 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1828 // Remove the key if there are no outstanding invitations.
1832 if(mesh->invitation_key) {
1833 ecdsa_free(mesh->invitation_key);
1834 mesh->invitation_key = NULL;
1838 if(mesh->invitation_key) {
1839 pthread_mutex_unlock(&(mesh->mesh_mutex));
1843 // Create a new key if necessary.
1844 FILE *f = fopen(filename, "rb");
1847 if(errno != ENOENT) {
1848 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1849 meshlink_errno = MESHLINK_ESTORAGE;
1850 pthread_mutex_unlock(&(mesh->mesh_mutex));
1854 mesh->invitation_key = ecdsa_generate();
1856 if(!mesh->invitation_key) {
1857 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1858 meshlink_errno = MESHLINK_EINTERNAL;
1859 pthread_mutex_unlock(&(mesh->mesh_mutex));
1863 f = fopen(filename, "wb");
1866 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1867 meshlink_errno = MESHLINK_ESTORAGE;
1868 pthread_mutex_unlock(&(mesh->mesh_mutex));
1872 chmod(filename, 0600);
1873 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1876 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1879 if(!mesh->invitation_key) {
1880 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1881 meshlink_errno = MESHLINK_ESTORAGE;
1885 pthread_mutex_unlock(&(mesh->mesh_mutex));
1886 return mesh->invitation_key;
1889 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1890 if(!mesh || !node || !address) {
1891 meshlink_errno = MESHLINK_EINVAL;
1895 if(!is_valid_hostname(address)) {
1896 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1897 meshlink_errno = MESHLINK_EINVAL;
1901 if(port && !is_valid_port(port)) {
1902 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1903 meshlink_errno = MESHLINK_EINVAL;
1907 char *canonical_address;
1910 xasprintf(&canonical_address, "%s %s", address, port);
1912 canonical_address = xstrdup(address);
1915 pthread_mutex_lock(&(mesh->mesh_mutex));
1916 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1917 pthread_mutex_unlock(&(mesh->mesh_mutex));
1919 free(canonical_address);
1923 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1924 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1927 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1929 meshlink_errno = MESHLINK_EINVAL;
1933 char *address = meshlink_get_external_address(mesh);
1941 pthread_mutex_lock(&(mesh->mesh_mutex));
1942 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1943 pthread_mutex_unlock(&(mesh->mesh_mutex));
1949 int meshlink_get_port(meshlink_handle_t *mesh) {
1951 meshlink_errno = MESHLINK_EINVAL;
1956 meshlink_errno = MESHLINK_EINTERNAL;
1960 return atoi(mesh->myport);
1963 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1964 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1965 meshlink_errno = MESHLINK_EINVAL;
1969 if(mesh->myport && port == atoi(mesh->myport)) {
1973 if(!try_bind(port)) {
1974 meshlink_errno = MESHLINK_ENETWORK;
1980 pthread_mutex_lock(&(mesh->mesh_mutex));
1982 if(mesh->threadstarted) {
1983 meshlink_errno = MESHLINK_EINVAL;
1987 close_network_connections(mesh);
1988 exit_configuration(&mesh->config);
1991 snprintf(portstr, sizeof(portstr), "%d", port);
1992 portstr[sizeof(portstr) - 1] = 0;
1994 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1996 init_configuration(&mesh->config);
1998 if(!read_server_config(mesh)) {
1999 meshlink_errno = MESHLINK_ESTORAGE;
2000 } else if(!setup_network(mesh)) {
2001 meshlink_errno = MESHLINK_ENETWORK;
2007 pthread_mutex_unlock(&(mesh->mesh_mutex));
2012 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2013 mesh->invitation_timeout = timeout;
2016 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
2018 meshlink_errno = MESHLINK_EINVAL;
2022 pthread_mutex_lock(&(mesh->mesh_mutex));
2024 // Check validity of the new node's name
2025 if(!check_id(name)) {
2026 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2027 meshlink_errno = MESHLINK_EINVAL;
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2032 // Ensure no host configuration file with that name exists
2033 char filename[PATH_MAX];
2034 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2036 if(!access(filename, F_OK)) {
2037 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2038 meshlink_errno = MESHLINK_EEXIST;
2039 pthread_mutex_unlock(&(mesh->mesh_mutex));
2043 // Ensure no other nodes know about this name
2044 if(meshlink_get_node(mesh, name)) {
2045 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2046 meshlink_errno = MESHLINK_EEXIST;
2047 pthread_mutex_unlock(&(mesh->mesh_mutex));
2051 // Get the local address
2052 char *address = get_my_hostname(mesh, flags);
2055 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2056 meshlink_errno = MESHLINK_ERESOLV;
2057 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 if(!refresh_invitation_key(mesh)) {
2062 meshlink_errno = MESHLINK_EINTERNAL;
2063 pthread_mutex_unlock(&(mesh->mesh_mutex));
2069 // Create a hash of the key.
2070 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2071 sha512(fingerprint, strlen(fingerprint), hash);
2072 b64encode_urlsafe(hash, hash, 18);
2074 // Create a random cookie for this invitation.
2076 randomize(cookie, 18);
2078 // Create a filename that doesn't reveal the cookie itself
2079 char buf[18 + strlen(fingerprint)];
2080 char cookiehash[64];
2081 memcpy(buf, cookie, 18);
2082 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2083 sha512(buf, sizeof(buf), cookiehash);
2084 b64encode_urlsafe(cookiehash, cookiehash, 18);
2086 b64encode_urlsafe(cookie, cookie, 18);
2090 // Create a file containing the details of the invitation.
2091 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2092 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2095 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2096 meshlink_errno = MESHLINK_ESTORAGE;
2097 pthread_mutex_unlock(&(mesh->mesh_mutex));
2101 FILE *f = fdopen(ifd, "w");
2107 // Fill in the details.
2108 fprintf(f, "Name = %s\n", name);
2109 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2111 // Copy Broadcast and Mode
2112 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2113 FILE *tc = fopen(filename, "r");
2118 while(fgets(buf, sizeof(buf), tc)) {
2119 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2120 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2123 // Make sure there is a newline character.
2124 if(!strchr(buf, '\n')) {
2132 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2133 meshlink_errno = MESHLINK_ESTORAGE;
2134 pthread_mutex_unlock(&(mesh->mesh_mutex));
2138 fprintf(f, "#---------------------------------------------------------------#\n");
2139 fprintf(f, "Name = %s\n", mesh->self->name);
2141 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2145 // Create an URL from the local address, key hash and cookie
2147 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2150 pthread_mutex_unlock(&(mesh->mesh_mutex));
2154 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
2155 return meshlink_invite_ex(mesh, name, 0);
2158 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2159 if(!mesh || !invitation) {
2160 meshlink_errno = MESHLINK_EINVAL;
2164 pthread_mutex_lock(&(mesh->mesh_mutex));
2166 //Before doing meshlink_join make sure we are not connected to another mesh
2167 if(mesh->threadstarted) {
2168 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2169 meshlink_errno = MESHLINK_EINVAL;
2170 pthread_mutex_unlock(&(mesh->mesh_mutex));
2174 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2175 char copy[strlen(invitation) + 1];
2176 strcpy(copy, invitation);
2178 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2180 char *slash = strchr(copy, '/');
2188 if(strlen(slash) != 48) {
2192 char *address = copy;
2195 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2199 // Generate a throw-away key for the invitation.
2200 ecdsa_t *key = ecdsa_generate();
2203 meshlink_errno = MESHLINK_EINTERNAL;
2204 pthread_mutex_unlock(&(mesh->mesh_mutex));
2208 char *b64key = ecdsa_get_base64_public_key(key);
2212 while(address && *address) {
2213 // We allow commas in the address part to support multiple addresses in one invitation URL.
2214 comma = strchr(address, ',');
2220 // Split of the port
2221 port = strrchr(address, ':');
2229 // IPv6 address are enclosed in brackets, per RFC 3986
2230 if(*address == '[') {
2232 char *bracket = strchr(address, ']');
2245 // Connect to the meshlink daemon mentioned in the URL.
2246 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2249 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2250 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2252 if(mesh->sock == -1) {
2253 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2254 meshlink_errno = MESHLINK_ENETWORK;
2258 set_timeout(mesh->sock, 5000);
2260 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2261 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2262 meshlink_errno = MESHLINK_ENETWORK;
2263 closesocket(mesh->sock);
2271 meshlink_errno = MESHLINK_ERESOLV;
2274 if(mesh->sock != -1 || !comma) {
2281 if(mesh->sock == -1) {
2282 pthread_mutex_unlock(&mesh->mesh_mutex);
2286 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2288 // Tell him we have an invitation, and give him our throw-away key.
2292 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2293 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2294 closesocket(mesh->sock);
2295 meshlink_errno = MESHLINK_ENETWORK;
2296 pthread_mutex_unlock(&(mesh->mesh_mutex));
2302 char hisname[4096] = "";
2303 int code, hismajor, hisminor = 0;
2305 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) {
2306 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2307 closesocket(mesh->sock);
2308 meshlink_errno = MESHLINK_ENETWORK;
2309 pthread_mutex_unlock(&(mesh->mesh_mutex));
2313 // Check if the hash of the key he gave us matches the hash in the URL.
2314 char *fingerprint = mesh->line + 2;
2317 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2318 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2319 meshlink_errno = MESHLINK_EINTERNAL;
2320 pthread_mutex_unlock(&(mesh->mesh_mutex));
2324 if(memcmp(hishash, mesh->hash, 18)) {
2325 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2326 meshlink_errno = MESHLINK_EPEER;
2327 pthread_mutex_unlock(&(mesh->mesh_mutex));
2332 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2335 meshlink_errno = MESHLINK_EINTERNAL;
2336 pthread_mutex_unlock(&(mesh->mesh_mutex));
2340 // Start an SPTPS session
2341 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2342 meshlink_errno = MESHLINK_EINTERNAL;
2343 pthread_mutex_unlock(&(mesh->mesh_mutex));
2347 // Feed rest of input buffer to SPTPS
2348 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2349 meshlink_errno = MESHLINK_EPEER;
2350 pthread_mutex_unlock(&(mesh->mesh_mutex));
2356 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2358 if(errno == EINTR) {
2362 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2363 meshlink_errno = MESHLINK_ENETWORK;
2364 pthread_mutex_unlock(&(mesh->mesh_mutex));
2368 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2369 meshlink_errno = MESHLINK_EPEER;
2370 pthread_mutex_unlock(&(mesh->mesh_mutex));
2375 sptps_stop(&mesh->sptps);
2378 closesocket(mesh->sock);
2380 if(!mesh->success) {
2381 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2382 meshlink_errno = MESHLINK_EPEER;
2383 pthread_mutex_unlock(&(mesh->mesh_mutex));
2387 pthread_mutex_unlock(&(mesh->mesh_mutex));
2391 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2392 meshlink_errno = MESHLINK_EINVAL;
2393 pthread_mutex_unlock(&(mesh->mesh_mutex));
2397 char *meshlink_export(meshlink_handle_t *mesh) {
2399 meshlink_errno = MESHLINK_EINVAL;
2403 pthread_mutex_lock(&(mesh->mesh_mutex));
2405 char filename[PATH_MAX];
2406 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2407 FILE *f = fopen(filename, "r");
2410 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2411 meshlink_errno = MESHLINK_ESTORAGE;
2412 pthread_mutex_unlock(&(mesh->mesh_mutex));
2416 fseek(f, 0, SEEK_END);
2417 int fsize = ftell(f);
2420 size_t len = fsize + 9 + strlen(mesh->self->name);
2421 char *buf = xmalloc(len);
2422 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2424 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2425 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2428 meshlink_errno = MESHLINK_ESTORAGE;
2429 pthread_mutex_unlock(&(mesh->mesh_mutex));
2436 pthread_mutex_unlock(&(mesh->mesh_mutex));
2440 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2441 if(!mesh || !data) {
2442 meshlink_errno = MESHLINK_EINVAL;
2446 pthread_mutex_lock(&(mesh->mesh_mutex));
2448 if(strncmp(data, "Name = ", 7)) {
2449 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2450 meshlink_errno = MESHLINK_EPEER;
2451 pthread_mutex_unlock(&(mesh->mesh_mutex));
2455 char *end = strchr(data + 7, '\n');
2458 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2459 meshlink_errno = MESHLINK_EPEER;
2460 pthread_mutex_unlock(&(mesh->mesh_mutex));
2464 int len = end - (data + 7);
2466 memcpy(name, data + 7, len);
2469 if(!check_id(name)) {
2470 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2471 meshlink_errno = MESHLINK_EPEER;
2472 pthread_mutex_unlock(&(mesh->mesh_mutex));
2476 char filename[PATH_MAX];
2477 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2479 if(!access(filename, F_OK)) {
2480 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2481 meshlink_errno = MESHLINK_EEXIST;
2482 pthread_mutex_unlock(&(mesh->mesh_mutex));
2486 if(errno != ENOENT) {
2487 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2488 meshlink_errno = MESHLINK_ESTORAGE;
2489 pthread_mutex_unlock(&(mesh->mesh_mutex));
2493 FILE *f = fopen(filename, "w");
2496 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2497 meshlink_errno = MESHLINK_ESTORAGE;
2498 pthread_mutex_unlock(&(mesh->mesh_mutex));
2502 fwrite(end + 1, strlen(end + 1), 1, f);
2505 load_all_nodes(mesh);
2507 pthread_mutex_unlock(&(mesh->mesh_mutex));
2511 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2512 if(!mesh || !node) {
2513 meshlink_errno = MESHLINK_EINVAL;
2517 pthread_mutex_lock(&(mesh->mesh_mutex));
2521 n->status.blacklisted = true;
2522 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2524 //Make blacklisting persistent in the config file
2525 append_config_file(mesh, n->name, "blacklisted", "yes");
2527 //Immediately terminate any connections we have with the blacklisted node
2528 for list_each(connection_t, c, mesh->connections) {
2530 terminate_connection(mesh, c, c->status.active);
2534 pthread_mutex_unlock(&(mesh->mesh_mutex));
2537 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2538 if(!mesh || !node) {
2539 meshlink_errno = MESHLINK_EINVAL;
2543 pthread_mutex_lock(&(mesh->mesh_mutex));
2545 node_t *n = (node_t *)node;
2546 n->status.blacklisted = false;
2548 //TODO: remove blacklisted = yes from the config file
2550 pthread_mutex_unlock(&(mesh->mesh_mutex));
2554 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2555 mesh->default_blacklist = blacklist;
2558 /* Hint that a hostname may be found at an address
2559 * See header file for detailed comment.
2561 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2562 if(!mesh || !node || !addr) {
2566 // Ignore hints about ourself.
2567 if((node_t *)node == mesh->self) {
2571 pthread_mutex_lock(&(mesh->mesh_mutex));
2573 char *host = NULL, *port = NULL, *str = NULL;
2574 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2577 xasprintf(&str, "%s %s", host, port);
2579 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2580 modify_config_file(mesh, node->name, "Address", str, 5);
2582 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2590 pthread_mutex_unlock(&(mesh->mesh_mutex));
2591 // @TODO do we want to fire off a connection attempt right away?
2594 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2596 node_t *n = utcp->priv;
2597 meshlink_handle_t *mesh = n->mesh;
2598 return mesh->channel_accept_cb;
2601 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2602 meshlink_channel_t *channel = connection->priv;
2608 node_t *n = channel->node;
2609 meshlink_handle_t *mesh = n->mesh;
2611 if(n->status.destroyed) {
2612 meshlink_channel_close(mesh, channel);
2613 } else if(channel->receive_cb) {
2614 channel->receive_cb(mesh, channel, data, len);
2620 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2621 node_t *n = utcp_connection->utcp->priv;
2627 meshlink_handle_t *mesh = n->mesh;
2629 if(!mesh->channel_accept_cb) {
2633 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2635 channel->c = utcp_connection;
2637 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2638 utcp_accept(utcp_connection, channel_recv, channel);
2644 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2645 node_t *n = utcp->priv;
2647 if(n->status.destroyed) {
2651 meshlink_handle_t *mesh = n->mesh;
2652 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2655 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2656 if(!mesh || !channel) {
2657 meshlink_errno = MESHLINK_EINVAL;
2661 channel->receive_cb = cb;
2664 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2666 node_t *n = (node_t *)source;
2672 utcp_recv(n->utcp, data, len);
2675 static void channel_poll(struct utcp_connection *connection, size_t len) {
2676 meshlink_channel_t *channel = connection->priv;
2682 node_t *n = channel->node;
2683 meshlink_handle_t *mesh = n->mesh;
2685 if(channel->poll_cb) {
2686 channel->poll_cb(mesh, channel, len);
2690 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2692 channel->poll_cb = cb;
2693 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2696 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2698 meshlink_errno = MESHLINK_EINVAL;
2702 pthread_mutex_lock(&mesh->mesh_mutex);
2703 mesh->channel_accept_cb = cb;
2704 mesh->receive_cb = channel_receive;
2706 for splay_each(node_t, n, mesh->nodes) {
2707 if(!n->utcp && n != mesh->self) {
2708 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2712 pthread_mutex_unlock(&mesh->mesh_mutex);
2715 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) {
2717 abort(); // TODO: handle non-NULL data
2720 if(!mesh || !node) {
2721 meshlink_errno = MESHLINK_EINVAL;
2725 node_t *n = (node_t *)node;
2728 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2729 mesh->receive_cb = channel_receive;
2732 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2737 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2739 channel->receive_cb = cb;
2740 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2743 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2751 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) {
2752 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2755 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2756 if(!mesh || !channel) {
2757 meshlink_errno = MESHLINK_EINVAL;
2761 utcp_shutdown(channel->c, direction);
2764 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2765 if(!mesh || !channel) {
2766 meshlink_errno = MESHLINK_EINVAL;
2770 utcp_close(channel->c);
2774 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2775 if(!mesh || !channel) {
2776 meshlink_errno = MESHLINK_EINVAL;
2785 meshlink_errno = MESHLINK_EINVAL;
2789 // TODO: more finegrained locking.
2790 // Ideally we want to put the data into the UTCP connection's send buffer.
2791 // Then, preferrably only if there is room in the receiver window,
2792 // kick the meshlink thread to go send packets.
2794 pthread_mutex_lock(&mesh->mesh_mutex);
2795 ssize_t retval = utcp_send(channel->c, data, len);
2796 pthread_mutex_unlock(&mesh->mesh_mutex);
2799 meshlink_errno = MESHLINK_ENETWORK;
2805 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2806 if(!mesh || !channel) {
2807 meshlink_errno = MESHLINK_EINVAL;
2811 return channel->c->flags;
2814 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2815 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2816 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2819 if(mesh->node_status_cb) {
2820 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2824 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2825 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2829 n->status.duplicate = true;
2830 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2833 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2837 meshlink_errno = MESHLINK_EINVAL;
2841 pthread_mutex_lock(&mesh->mesh_mutex);
2843 if(mesh->discovery == enable) {
2847 if(mesh->threadstarted) {
2849 discovery_start(mesh);
2851 discovery_stop(mesh);
2855 mesh->discovery = enable;
2858 pthread_mutex_unlock(&mesh->mesh_mutex);
2862 meshlink_errno = MESHLINK_ENOTSUP;
2866 static void __attribute__((constructor)) meshlink_init(void) {
2869 randomize(&seed, sizeof(seed));
2873 static void __attribute__((destructor)) meshlink_exit(void) {
2877 /// Device class traits
2878 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2879 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2880 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2881 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2882 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN