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"
44 #include "ed25519/sha512.h"
45 #include "discovery.h"
48 #define MSG_NOSIGNAL 0
51 __thread meshlink_errno_t meshlink_errno;
52 meshlink_log_cb_t global_log_cb;
53 meshlink_log_level_t global_log_level;
55 //TODO: this can go away completely
56 const var_t variables[] = {
57 /* Server configuration */
58 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
60 /* Host configuration */
61 {"CanonicalAddress", VAR_HOST},
62 {"Address", VAR_HOST | VAR_MULTIPLE},
63 {"ECDSAPublicKey", VAR_HOST},
68 static bool fcopy(FILE *out, const char *filename) {
69 FILE *in = fopen(filename, "r");
72 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
79 while((len = fread(buf, 1, sizeof(buf), in))) {
80 fwrite(buf, len, 1, out);
87 static int rstrip(char *value) {
88 int len = strlen(value);
90 while(len && strchr("\t\r\n ", value[len - 1])) {
97 static void scan_for_canonical_address(const char *filename, char **hostname, char **port) {
100 if(!filename || (*hostname && *port)) {
104 FILE *f = fopen(filename, "r");
110 while(fgets(line, sizeof(line), f)) {
116 p += strcspn(p, "\t =");
122 q = p + strspn(p, "\t ");
125 q += 1 + strspn(q + 1, "\t ");
128 // q is now pointing to the hostname
130 p = q + strcspn(q, "\t ");
136 p += strspn(p, "\t ");
137 p[strcspn(p, "\t ")] = 0;
138 // p is now pointing to the port, if present
140 if(!*port && !strcasecmp(line, "Port")) {
142 } else if(!strcasecmp(line, "CanonicalAddress")) {
143 *hostname = xstrdup(q);
151 if(*hostname && *port) {
159 static bool is_valid_hostname(const char *hostname) {
164 for(const char *p = hostname; *p; p++) {
165 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
173 static bool is_valid_port(const char *port) {
180 unsigned long int result = strtoul(port, &end, 10);
181 return result && result < 65536 && !*end;
184 for(const char *p = port; *p; p++) {
185 if(!(isalnum(*p) || *p == '-')) {
193 static void set_timeout(int sock, int timeout) {
198 tv.tv_sec = timeout / 1000;
199 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
201 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
202 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
205 // Find out what local address a socket would use if we connect to the given address.
206 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
207 // of both endpoints, but this will actually not send any UDP packet.
208 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
209 struct addrinfo *rai = NULL;
210 const struct addrinfo hint = {
211 .ai_family = AF_UNSPEC,
212 .ai_socktype = SOCK_DGRAM,
213 .ai_protocol = IPPROTO_UDP,
216 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
220 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
227 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
234 struct sockaddr_storage sn;
235 socklen_t sl = sizeof(sn);
237 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
241 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
248 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
249 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
252 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
253 char *hostname = NULL;
255 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
256 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
257 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
260 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
261 if(family != AF_UNSPEC && aip->ai_family != family) {
265 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
268 set_timeout(s, 5000);
270 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
277 send(s, request, sizeof(request) - 1, 0);
278 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
283 if(line[len - 1] == '\n') {
287 char *p = strrchr(line, '\n');
290 hostname = xstrdup(p + 1);
306 // Check that the hostname is reasonable
307 if(hostname && !is_valid_hostname(hostname)) {
313 meshlink_errno = MESHLINK_ERESOLV;
319 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
322 // Determine address of the local interface used for outgoing connections.
323 char localaddr[NI_MAXHOST];
324 bool success = false;
326 if(family == AF_INET) {
327 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
328 } else if(family == AF_INET6) {
329 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
333 meshlink_errno = MESHLINK_ENETWORK;
337 return xstrdup(localaddr);
340 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
341 for(int i = 0; i < n; i++) {
346 // Ignore duplicate hostnames
349 for(int j = 0; j < i; j++) {
354 if(strcmp(host[i], host[j])) {
358 if(strcmp(port[i], port[j])) {
376 // This gets the hostname part for use in invitation URLs
377 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
378 char *hostname[4] = {NULL};
379 char *port[4] = {NULL};
380 char *hostport = NULL;
382 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
383 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
386 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
387 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
390 fprintf(stderr, "flags = %u\n", flags);
392 // Add local addresses if requested
393 if(flags & MESHLINK_INVITE_LOCAL) {
394 if(flags & MESHLINK_INVITE_IPV4) {
395 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
398 if(flags & MESHLINK_INVITE_IPV6) {
399 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
403 // Add public/canonical addresses if requested
404 if(flags & MESHLINK_INVITE_PUBLIC) {
405 // Try the CanonicalAddress first
406 char filename[PATH_MAX] = "";
407 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
408 scan_for_canonical_address(filename, &hostname[2], &port[2]);
411 if(flags & MESHLINK_INVITE_IPV4) {
412 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
415 if(flags & MESHLINK_INVITE_IPV6) {
416 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
421 for(int i = 0; i < 4; i++) {
422 // Ensure we always have a port number
423 if(hostname[i] && !port[i]) {
424 port[i] = xstrdup(mesh->myport);
428 remove_duplicate_hostnames(hostname, port, 4);
430 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
431 for(int i = 0; i < 4; i++) {
436 // Convert what we have to a sockaddr
437 struct addrinfo *ai_in, *ai_out;
438 struct addrinfo hint = {
439 .ai_family = AF_UNSPEC,
440 .ai_flags = AI_NUMERICSERV,
441 .ai_socktype = SOCK_STREAM,
443 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
449 // Convert it to a hostname
450 char resolved_host[NI_MAXHOST];
451 char resolved_port[NI_MAXSERV];
452 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
459 // Convert the hostname back to a sockaddr
460 hint.ai_family = ai_in->ai_family;
461 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
468 // Check if it's still the same sockaddr
469 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
471 freeaddrinfo(ai_out);
475 // Yes: replace the hostname with the resolved one
477 hostname[i] = xstrdup(resolved_host);
480 freeaddrinfo(ai_out);
484 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
485 remove_duplicate_hostnames(hostname, port, 4);
487 // Concatenate all unique address to the hostport string
488 for(int i = 0; i < 4; i++) {
493 // Ensure we have the same addresses in our own host config file.
495 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
496 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
499 // Append the address to the hostport string
501 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
503 hostport = newhostport;
512 static char *get_line(const char **data) {
513 if(!data || !*data) {
522 static char line[1024];
523 const char *end = strchr(*data, '\n');
524 size_t len = end ? (size_t)(end - *data) : strlen(*data);
526 if(len >= sizeof(line)) {
527 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
531 if(len && !isprint(**data)) {
535 memcpy(line, *data, len);
547 static char *get_value(const char *data, const char *var) {
548 char *line = get_line(&data);
554 char *sep = line + strcspn(line, " \t=");
555 char *val = sep + strspn(sep, " \t");
558 val += 1 + strspn(val + 1, " \t");
563 if(strcasecmp(line, var)) {
570 static bool try_bind(int port) {
571 struct addrinfo *ai = NULL;
572 struct addrinfo hint = {
573 .ai_flags = AI_PASSIVE,
574 .ai_family = AF_UNSPEC,
575 .ai_socktype = SOCK_STREAM,
576 .ai_protocol = IPPROTO_TCP,
580 snprintf(portstr, sizeof(portstr), "%d", port);
582 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
587 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
594 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
609 int check_port(meshlink_handle_t *mesh) {
610 for(int i = 0; i < 1000; i++) {
611 int port = 0x1000 + (rand() & 0x7fff);
614 char filename[PATH_MAX];
615 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
616 FILE *f = fopen(filename, "a");
619 meshlink_errno = MESHLINK_ESTORAGE;
620 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
624 fprintf(f, "Port = %d\n", port);
630 meshlink_errno = MESHLINK_ENETWORK;
631 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
635 static void deltree(const char *dirname) {
636 DIR *d = opendir(dirname);
641 while((ent = readdir(d))) {
642 if(ent->d_name[0] == '.') {
646 char filename[PATH_MAX];
647 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
649 if(unlink(filename)) {
660 static bool finalize_join(meshlink_handle_t *mesh) {
661 char *name = xstrdup(get_value(mesh->data, "Name"));
664 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
668 if(!check_id(name)) {
669 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
673 char filename[PATH_MAX];
674 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
676 FILE *f = fopen(filename, "w");
679 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
683 fprintf(f, "Name = %s\n", name);
685 // Wipe all old host config files and invitations
686 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
689 if(mkdir(filename, 0777) && errno != EEXIST) {
690 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
694 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
697 // Create a new host config file for ourself
698 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
699 FILE *fh = fopen(filename, "w");
702 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
707 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
708 // Other chunks go unfiltered to their respective host config files
709 const char *p = mesh->data;
712 while((l = get_line(&p))) {
718 // Split line into variable and value
719 int len = strcspn(l, "\t =");
721 value += strspn(value, "\t ");
725 value += strspn(value, "\t ");
731 if(!strcasecmp(l, "Name"))
732 if(strcmp(value, name)) {
736 } else if(!strcasecmp(l, "NetName")) {
740 // Check the list of known variables
744 for(i = 0; variables[i].name; i++) {
745 if(strcasecmp(l, variables[i].name)) {
753 // Ignore unknown and unsafe variables
755 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
757 } else if(!(variables[i].type & VAR_SAFE)) {
758 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
762 // Copy the safe variable to the right config file
763 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
768 while(l && !strcasecmp(l, "Name")) {
769 if(!check_id(value)) {
770 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
774 if(!strcmp(value, name)) {
775 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
779 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
780 f = fopen(filename, "w");
783 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
787 while((l = get_line(&p))) {
788 if(!strcmp(l, "#---------------------------------------------------------------#")) {
792 int len = strcspn(l, "\t =");
794 if(len == 4 && !strncasecmp(l, "Name", 4)) {
796 value += strspn(value, "\t ");
800 value += strspn(value, "\t ");
814 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
821 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
822 fprintf(fh, "Port = %s\n", mesh->myport);
826 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
830 free(mesh->self->name);
831 free(mesh->self->connection->name);
832 mesh->name = xstrdup(name);
833 mesh->self->name = xstrdup(name);
834 mesh->self->connection->name = name;
836 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
838 load_all_nodes(mesh);
843 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
845 meshlink_handle_t *mesh = handle;
846 const char *ptr = data;
849 int result = send(mesh->sock, ptr, len, 0);
851 if(result == -1 && errno == EINTR) {
853 } else if(result <= 0) {
864 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
865 meshlink_handle_t *mesh = handle;
868 case SPTPS_HANDSHAKE:
869 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
872 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
873 memcpy(mesh->data + mesh->thedatalen, msg, len);
874 mesh->thedatalen += len;
875 mesh->data[mesh->thedatalen] = 0;
879 mesh->thedatalen = 0;
880 return finalize_join(mesh);
883 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
884 shutdown(mesh->sock, SHUT_RDWR);
885 mesh->success = true;
895 static bool recvline(meshlink_handle_t *mesh, size_t len) {
896 char *newline = NULL;
902 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
903 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
905 if(result == -1 && errno == EINTR) {
907 } else if(result <= 0) {
911 mesh->blen += result;
914 if((size_t)(newline - mesh->buffer) >= len) {
918 len = newline - mesh->buffer;
920 memcpy(mesh->line, mesh->buffer, len);
922 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
923 mesh->blen -= len + 1;
927 static bool sendline(int fd, char *format, ...) {
928 static char buffer[4096];
933 va_start(ap, format);
934 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
937 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
945 int result = send(fd, p, blen, MSG_NOSIGNAL);
947 if(result == -1 && errno == EINTR) {
949 } else if(result <= 0) {
960 static const char *errstr[] = {
961 [MESHLINK_OK] = "No error",
962 [MESHLINK_EINVAL] = "Invalid argument",
963 [MESHLINK_ENOMEM] = "Out of memory",
964 [MESHLINK_ENOENT] = "No such node",
965 [MESHLINK_EEXIST] = "Node already exists",
966 [MESHLINK_EINTERNAL] = "Internal error",
967 [MESHLINK_ERESOLV] = "Could not resolve hostname",
968 [MESHLINK_ESTORAGE] = "Storage error",
969 [MESHLINK_ENETWORK] = "Network error",
970 [MESHLINK_EPEER] = "Error communicating with peer",
971 [MESHLINK_ENOTSUP] = "Operation not supported",
972 [MESHLINK_EBUSY] = "MeshLink instance already in use",
975 const char *meshlink_strerror(meshlink_errno_t err) {
976 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
977 return "Invalid error code";
983 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
986 char pubname[PATH_MAX], privname[PATH_MAX];
988 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
990 if(!(key = ecdsa_generate())) {
991 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
992 meshlink_errno = MESHLINK_EINTERNAL;
995 logger(mesh, MESHLINK_DEBUG, "Done.\n");
998 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
999 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
1000 meshlink_errno = MESHLINK_ESTORAGE;
1004 f = fopen(privname, "wb");
1007 meshlink_errno = MESHLINK_ESTORAGE;
1012 fchmod(fileno(f), 0600);
1015 if(!ecdsa_write_pem_private_key(key, f)) {
1016 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
1019 meshlink_errno = MESHLINK_EINTERNAL;
1025 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
1026 f = fopen(pubname, "a");
1029 meshlink_errno = MESHLINK_ESTORAGE;
1033 char *pubkey = ecdsa_get_base64_public_key(key);
1034 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
1043 static struct timeval idle(event_loop_t *loop, void *data) {
1045 meshlink_handle_t *mesh = data;
1046 struct timeval t, tmin = {3600, 0};
1048 for splay_each(node_t, n, mesh->nodes) {
1053 t = utcp_timeout(n->utcp);
1055 if(timercmp(&t, &tmin, <)) {
1063 // Get our local address(es) by simulating connecting to an Internet host.
1064 static void add_local_addresses(meshlink_handle_t *mesh) {
1065 char host[NI_MAXHOST];
1066 char entry[MAX_STRING_SIZE];
1070 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
1071 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1072 append_config_file(mesh, mesh->name, "Address", entry);
1077 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
1078 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
1079 append_config_file(mesh, mesh->name, "Address", entry);
1083 static bool meshlink_setup(meshlink_handle_t *mesh) {
1084 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1085 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1086 meshlink_errno = MESHLINK_ESTORAGE;
1090 char filename[PATH_MAX];
1091 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
1093 if(mkdir(filename, 0777) && errno != EEXIST) {
1094 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1095 meshlink_errno = MESHLINK_ESTORAGE;
1099 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1101 if(!access(filename, F_OK)) {
1102 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1103 meshlink_errno = MESHLINK_EEXIST;
1107 FILE *f = fopen(filename, "w");
1110 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1111 meshlink_errno = MESHLINK_ESTORAGE;
1115 fprintf(f, "Name = %s\n", mesh->name);
1118 if(!ecdsa_keygen(mesh)) {
1119 meshlink_errno = MESHLINK_EINTERNAL;
1124 if(check_port(mesh) == 0) {
1125 meshlink_errno = MESHLINK_ENETWORK;
1133 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1134 // Validate arguments provided by the application
1135 bool usingname = false;
1137 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1139 if(!confbase || !*confbase) {
1140 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1141 meshlink_errno = MESHLINK_EINVAL;
1145 if(!appname || !*appname) {
1146 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1147 meshlink_errno = MESHLINK_EINVAL;
1151 if(strchr(appname, ' ')) {
1152 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1153 meshlink_errno = MESHLINK_EINVAL;
1157 if(!name || !*name) {
1158 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1160 } else { //check name only if there is a name != NULL
1162 if(!check_id(name)) {
1163 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1164 meshlink_errno = MESHLINK_EINVAL;
1171 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1172 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1173 meshlink_errno = MESHLINK_EINVAL;
1177 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1178 mesh->confbase = xstrdup(confbase);
1179 mesh->appname = xstrdup(appname);
1180 mesh->devclass = devclass;
1181 mesh->discovery = true;
1182 mesh->invitation_timeout = 604800; // 1 week
1185 mesh->name = xstrdup(name);
1189 pthread_mutexattr_t attr;
1190 pthread_mutexattr_init(&attr);
1191 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1192 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1194 mesh->threadstarted = false;
1195 event_loop_init(&mesh->loop);
1196 mesh->loop.data = mesh;
1198 meshlink_queue_init(&mesh->outpacketqueue);
1200 // Check whether meshlink.conf already exists
1202 char filename[PATH_MAX];
1203 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1205 if(access(filename, R_OK)) {
1206 if(errno == ENOENT) {
1207 // If not, create it
1208 if(!meshlink_setup(mesh)) {
1209 // meshlink_errno is set by meshlink_setup()
1213 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1214 meshlink_close(mesh);
1215 meshlink_errno = MESHLINK_ESTORAGE;
1220 // Open the configuration file and lock it
1222 mesh->conffile = fopen(filename, "r");
1224 if(!mesh->conffile) {
1225 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1226 meshlink_close(mesh);
1227 meshlink_errno = MESHLINK_ESTORAGE;
1232 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1236 // TODO: use _locking()?
1239 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1240 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1241 meshlink_close(mesh);
1242 meshlink_errno = MESHLINK_EBUSY;
1248 // Read the configuration
1250 init_configuration(&mesh->config);
1252 if(!read_server_config(mesh)) {
1253 meshlink_close(mesh);
1254 meshlink_errno = MESHLINK_ESTORAGE;
1259 struct WSAData wsa_state;
1261 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1265 // Setup up everything
1266 // TODO: we should not open listening sockets yet
1268 if(!setup_network(mesh)) {
1269 meshlink_close(mesh);
1270 meshlink_errno = MESHLINK_ENETWORK;
1274 add_local_addresses(mesh);
1276 idle_set(&mesh->loop, idle, mesh);
1278 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1282 static void *meshlink_main_loop(void *arg) {
1283 meshlink_handle_t *mesh = arg;
1285 pthread_mutex_lock(&(mesh->mesh_mutex));
1287 try_outgoing_connections(mesh);
1289 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1291 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1293 pthread_mutex_unlock(&(mesh->mesh_mutex));
1297 bool meshlink_start(meshlink_handle_t *mesh) {
1299 meshlink_errno = MESHLINK_EINVAL;
1303 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1305 pthread_mutex_lock(&(mesh->mesh_mutex));
1307 if(mesh->threadstarted) {
1308 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1309 pthread_mutex_unlock(&(mesh->mesh_mutex));
1313 if(mesh->listen_socket[0].tcp.fd < 0) {
1314 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1315 meshlink_errno = MESHLINK_ENETWORK;
1319 mesh->thedatalen = 0;
1321 // TODO: open listening sockets first
1323 //Check that a valid name is set
1325 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1326 meshlink_errno = MESHLINK_EINVAL;
1327 pthread_mutex_unlock(&(mesh->mesh_mutex));
1331 // Start the main thread
1333 event_loop_start(&mesh->loop);
1335 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1336 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1337 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1338 meshlink_errno = MESHLINK_EINTERNAL;
1339 event_loop_stop(&mesh->loop);
1340 pthread_mutex_unlock(&(mesh->mesh_mutex));
1344 mesh->threadstarted = true;
1348 if(mesh->discovery) {
1349 discovery_start(mesh);
1354 pthread_mutex_unlock(&(mesh->mesh_mutex));
1358 void meshlink_stop(meshlink_handle_t *mesh) {
1360 meshlink_errno = MESHLINK_EINVAL;
1364 pthread_mutex_lock(&(mesh->mesh_mutex));
1365 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1370 if(mesh->discovery) {
1371 discovery_stop(mesh);
1376 // Shut down the main thread
1377 event_loop_stop(&mesh->loop);
1379 // Send ourselves a UDP packet to kick the event loop
1380 for(int i = 0; i < mesh->listen_sockets; i++) {
1382 socklen_t salen = sizeof(sa.sa);
1384 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1385 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1389 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1390 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1394 if(mesh->threadstarted) {
1395 // Wait for the main thread to finish
1396 pthread_mutex_unlock(&(mesh->mesh_mutex));
1397 pthread_join(mesh->thread, NULL);
1398 pthread_mutex_lock(&(mesh->mesh_mutex));
1400 mesh->threadstarted = false;
1403 // Close all metaconnections
1404 if(mesh->connections) {
1405 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1407 connection_t *c = node->data;
1409 terminate_connection(mesh, c, false);
1413 if(mesh->outgoings) {
1414 list_delete_list(mesh->outgoings);
1415 mesh->outgoings = NULL;
1418 pthread_mutex_unlock(&(mesh->mesh_mutex));
1421 void meshlink_close(meshlink_handle_t *mesh) {
1422 if(!mesh || !mesh->confbase) {
1423 meshlink_errno = MESHLINK_EINVAL;
1427 // stop can be called even if mesh has not been started
1428 meshlink_stop(mesh);
1430 // lock is not released after this
1431 pthread_mutex_lock(&(mesh->mesh_mutex));
1433 // Close and free all resources used.
1435 close_network_connections(mesh);
1437 logger(mesh, MESHLINK_INFO, "Terminating");
1439 exit_configuration(&mesh->config);
1440 event_loop_exit(&mesh->loop);
1444 if(mesh->confbase) {
1450 ecdsa_free(mesh->invitation_key);
1453 free(mesh->appname);
1454 free(mesh->confbase);
1455 pthread_mutex_destroy(&(mesh->mesh_mutex));
1457 if(mesh->conffile) {
1458 fclose(mesh->conffile);
1461 memset(mesh, 0, sizeof(*mesh));
1466 bool meshlink_destroy(const char *confbase) {
1468 meshlink_errno = MESHLINK_EINVAL;
1472 char filename[PATH_MAX];
1473 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1475 if(unlink(filename)) {
1476 if(errno == ENOENT) {
1477 meshlink_errno = MESHLINK_ENOENT;
1480 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1481 meshlink_errno = MESHLINK_ESTORAGE;
1491 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1493 meshlink_errno = MESHLINK_EINVAL;
1497 pthread_mutex_lock(&(mesh->mesh_mutex));
1498 mesh->receive_cb = cb;
1499 pthread_mutex_unlock(&(mesh->mesh_mutex));
1502 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1504 meshlink_errno = MESHLINK_EINVAL;
1508 pthread_mutex_lock(&(mesh->mesh_mutex));
1509 mesh->node_status_cb = cb;
1510 pthread_mutex_unlock(&(mesh->mesh_mutex));
1513 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1515 meshlink_errno = MESHLINK_EINVAL;
1519 pthread_mutex_lock(&(mesh->mesh_mutex));
1520 mesh->node_duplicate_cb = cb;
1521 pthread_mutex_unlock(&(mesh->mesh_mutex));
1524 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1526 pthread_mutex_lock(&(mesh->mesh_mutex));
1528 mesh->log_level = cb ? level : 0;
1529 pthread_mutex_unlock(&(mesh->mesh_mutex));
1532 global_log_level = cb ? level : 0;
1536 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1537 // Validate arguments
1538 if(!mesh || !destination || len >= MAXSIZE) {
1539 meshlink_errno = MESHLINK_EINVAL;
1548 meshlink_errno = MESHLINK_EINVAL;
1552 // Prepare the packet
1553 vpn_packet_t *packet = malloc(sizeof(*packet));
1556 meshlink_errno = MESHLINK_ENOMEM;
1560 packet->probe = false;
1561 packet->tcp = false;
1563 packet->src = mesh->self->id;
1564 packet->dst = ((node_t *)destination)->id;
1566 memcpy(packet->data, data, len);
1569 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1571 meshlink_errno = MESHLINK_ENOMEM;
1575 // Notify event loop
1576 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1581 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1583 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1589 mesh->self->in_packets++;
1590 mesh->self->in_bytes += packet->len;
1591 node_t *dest = lookup_node_id(mesh, packet->dst);
1594 send_packet(mesh, dest, packet);
1600 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1601 if(!mesh || !destination) {
1602 meshlink_errno = MESHLINK_EINVAL;
1606 pthread_mutex_lock(&(mesh->mesh_mutex));
1608 node_t *n = (node_t *)destination;
1610 if(!n->status.reachable) {
1611 pthread_mutex_unlock(&(mesh->mesh_mutex));
1614 } else if(n->mtuprobes > 30 && n->minmtu) {
1615 pthread_mutex_unlock(&(mesh->mesh_mutex));
1618 pthread_mutex_unlock(&(mesh->mesh_mutex));
1623 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1624 if(!mesh || !node) {
1625 meshlink_errno = MESHLINK_EINVAL;
1629 pthread_mutex_lock(&(mesh->mesh_mutex));
1631 node_t *n = (node_t *)node;
1633 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1634 meshlink_errno = MESHLINK_EINTERNAL;
1635 pthread_mutex_unlock(&(mesh->mesh_mutex));
1639 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1642 meshlink_errno = MESHLINK_EINTERNAL;
1645 pthread_mutex_unlock(&(mesh->mesh_mutex));
1649 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1651 meshlink_errno = MESHLINK_EINVAL;
1655 return (meshlink_node_t *)mesh->self;
1658 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1659 if(!mesh || !name) {
1660 meshlink_errno = MESHLINK_EINVAL;
1664 meshlink_node_t *node = NULL;
1666 pthread_mutex_lock(&(mesh->mesh_mutex));
1667 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1668 pthread_mutex_unlock(&(mesh->mesh_mutex));
1672 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1673 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1674 meshlink_errno = MESHLINK_EINVAL;
1678 meshlink_node_t **result;
1681 pthread_mutex_lock(&(mesh->mesh_mutex));
1683 *nmemb = mesh->nodes->count;
1684 result = realloc(nodes, *nmemb * sizeof(*nodes));
1687 meshlink_node_t **p = result;
1689 for splay_each(node_t, n, mesh->nodes) {
1690 *p++ = (meshlink_node_t *)n;
1695 meshlink_errno = MESHLINK_ENOMEM;
1698 pthread_mutex_unlock(&(mesh->mesh_mutex));
1703 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1704 if(!mesh || !data || !len || !signature || !siglen) {
1705 meshlink_errno = MESHLINK_EINVAL;
1709 if(*siglen < MESHLINK_SIGLEN) {
1710 meshlink_errno = MESHLINK_EINVAL;
1714 pthread_mutex_lock(&(mesh->mesh_mutex));
1716 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1717 meshlink_errno = MESHLINK_EINTERNAL;
1718 pthread_mutex_unlock(&(mesh->mesh_mutex));
1722 *siglen = MESHLINK_SIGLEN;
1723 pthread_mutex_unlock(&(mesh->mesh_mutex));
1727 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1728 if(!mesh || !data || !len || !signature) {
1729 meshlink_errno = MESHLINK_EINVAL;
1733 if(siglen != MESHLINK_SIGLEN) {
1734 meshlink_errno = MESHLINK_EINVAL;
1738 pthread_mutex_lock(&(mesh->mesh_mutex));
1742 struct node_t *n = (struct node_t *)source;
1743 node_read_ecdsa_public_key(mesh, n);
1746 meshlink_errno = MESHLINK_EINTERNAL;
1749 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1752 pthread_mutex_unlock(&(mesh->mesh_mutex));
1756 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1757 char filename[PATH_MAX];
1759 pthread_mutex_lock(&(mesh->mesh_mutex));
1761 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1763 if(mkdir(filename, 0700) && errno != EEXIST) {
1764 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1765 meshlink_errno = MESHLINK_ESTORAGE;
1766 pthread_mutex_unlock(&(mesh->mesh_mutex));
1770 // Count the number of valid invitations, clean up old ones
1771 DIR *dir = opendir(filename);
1774 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1775 meshlink_errno = MESHLINK_ESTORAGE;
1776 pthread_mutex_unlock(&(mesh->mesh_mutex));
1783 time_t deadline = time(NULL) - 604800; // 1 week in the past
1785 while((ent = readdir(dir))) {
1786 if(strlen(ent->d_name) != 24) {
1790 char invname[PATH_MAX];
1793 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1794 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1798 if(!stat(invname, &st)) {
1799 if(mesh->invitation_key && deadline < st.st_mtime) {
1805 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1811 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1813 meshlink_errno = MESHLINK_ESTORAGE;
1814 pthread_mutex_unlock(&(mesh->mesh_mutex));
1820 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1822 // Remove the key if there are no outstanding invitations.
1826 if(mesh->invitation_key) {
1827 ecdsa_free(mesh->invitation_key);
1828 mesh->invitation_key = NULL;
1832 if(mesh->invitation_key) {
1833 pthread_mutex_unlock(&(mesh->mesh_mutex));
1837 // Create a new key if necessary.
1838 FILE *f = fopen(filename, "rb");
1841 if(errno != ENOENT) {
1842 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1843 meshlink_errno = MESHLINK_ESTORAGE;
1844 pthread_mutex_unlock(&(mesh->mesh_mutex));
1848 mesh->invitation_key = ecdsa_generate();
1850 if(!mesh->invitation_key) {
1851 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1852 meshlink_errno = MESHLINK_EINTERNAL;
1853 pthread_mutex_unlock(&(mesh->mesh_mutex));
1857 f = fopen(filename, "wb");
1860 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1861 meshlink_errno = MESHLINK_ESTORAGE;
1862 pthread_mutex_unlock(&(mesh->mesh_mutex));
1866 chmod(filename, 0600);
1867 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1870 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1873 if(!mesh->invitation_key) {
1874 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1875 meshlink_errno = MESHLINK_ESTORAGE;
1879 pthread_mutex_unlock(&(mesh->mesh_mutex));
1880 return mesh->invitation_key;
1883 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1884 if(!mesh || !node || !address) {
1885 meshlink_errno = MESHLINK_EINVAL;
1889 if(!is_valid_hostname(address)) {
1890 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1891 meshlink_errno = MESHLINK_EINVAL;
1895 if(port && !is_valid_port(port)) {
1896 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1897 meshlink_errno = MESHLINK_EINVAL;
1901 char *canonical_address;
1904 xasprintf(&canonical_address, "%s %s", address, port);
1906 canonical_address = xstrdup(address);
1909 pthread_mutex_lock(&(mesh->mesh_mutex));
1910 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1911 pthread_mutex_unlock(&(mesh->mesh_mutex));
1913 free(canonical_address);
1917 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1918 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1921 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1923 meshlink_errno = MESHLINK_EINVAL;
1927 char *address = meshlink_get_external_address(mesh);
1935 pthread_mutex_lock(&(mesh->mesh_mutex));
1936 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1937 pthread_mutex_unlock(&(mesh->mesh_mutex));
1943 int meshlink_get_port(meshlink_handle_t *mesh) {
1945 meshlink_errno = MESHLINK_EINVAL;
1950 meshlink_errno = MESHLINK_EINTERNAL;
1954 return atoi(mesh->myport);
1957 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1958 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1959 meshlink_errno = MESHLINK_EINVAL;
1963 if(mesh->myport && port == atoi(mesh->myport)) {
1967 if(!try_bind(port)) {
1968 meshlink_errno = MESHLINK_ENETWORK;
1974 pthread_mutex_lock(&(mesh->mesh_mutex));
1976 if(mesh->threadstarted) {
1977 meshlink_errno = MESHLINK_EINVAL;
1981 close_network_connections(mesh);
1982 exit_configuration(&mesh->config);
1985 snprintf(portstr, sizeof(portstr), "%d", port);
1986 portstr[sizeof(portstr) - 1] = 0;
1988 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1990 init_configuration(&mesh->config);
1992 if(!read_server_config(mesh)) {
1993 meshlink_errno = MESHLINK_ESTORAGE;
1994 } else if(!setup_network(mesh)) {
1995 meshlink_errno = MESHLINK_ENETWORK;
2001 pthread_mutex_unlock(&(mesh->mesh_mutex));
2006 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2007 mesh->invitation_timeout = timeout;
2010 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
2012 meshlink_errno = MESHLINK_EINVAL;
2016 pthread_mutex_lock(&(mesh->mesh_mutex));
2018 // Check validity of the new node's name
2019 if(!check_id(name)) {
2020 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2021 meshlink_errno = MESHLINK_EINVAL;
2022 pthread_mutex_unlock(&(mesh->mesh_mutex));
2026 // Ensure no host configuration file with that name exists
2027 char filename[PATH_MAX];
2028 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2030 if(!access(filename, F_OK)) {
2031 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2032 meshlink_errno = MESHLINK_EEXIST;
2033 pthread_mutex_unlock(&(mesh->mesh_mutex));
2037 // Ensure no other nodes know about this name
2038 if(meshlink_get_node(mesh, name)) {
2039 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2040 meshlink_errno = MESHLINK_EEXIST;
2041 pthread_mutex_unlock(&(mesh->mesh_mutex));
2045 // Get the local address
2046 char *address = get_my_hostname(mesh, flags);
2049 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2050 meshlink_errno = MESHLINK_ERESOLV;
2051 pthread_mutex_unlock(&(mesh->mesh_mutex));
2055 if(!refresh_invitation_key(mesh)) {
2056 meshlink_errno = MESHLINK_EINTERNAL;
2057 pthread_mutex_unlock(&(mesh->mesh_mutex));
2063 // Create a hash of the key.
2064 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2065 sha512(fingerprint, strlen(fingerprint), hash);
2066 b64encode_urlsafe(hash, hash, 18);
2068 // Create a random cookie for this invitation.
2070 randomize(cookie, 18);
2072 // Create a filename that doesn't reveal the cookie itself
2073 char buf[18 + strlen(fingerprint)];
2074 char cookiehash[64];
2075 memcpy(buf, cookie, 18);
2076 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2077 sha512(buf, sizeof(buf), cookiehash);
2078 b64encode_urlsafe(cookiehash, cookiehash, 18);
2080 b64encode_urlsafe(cookie, cookie, 18);
2084 // Create a file containing the details of the invitation.
2085 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2086 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2089 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2090 meshlink_errno = MESHLINK_ESTORAGE;
2091 pthread_mutex_unlock(&(mesh->mesh_mutex));
2095 FILE *f = fdopen(ifd, "w");
2101 // Fill in the details.
2102 fprintf(f, "Name = %s\n", name);
2103 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2105 // Copy Broadcast and Mode
2106 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2107 FILE *tc = fopen(filename, "r");
2112 while(fgets(buf, sizeof(buf), tc)) {
2113 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2114 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2117 // Make sure there is a newline character.
2118 if(!strchr(buf, '\n')) {
2126 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2127 meshlink_errno = MESHLINK_ESTORAGE;
2128 pthread_mutex_unlock(&(mesh->mesh_mutex));
2132 fprintf(f, "#---------------------------------------------------------------#\n");
2133 fprintf(f, "Name = %s\n", mesh->self->name);
2135 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2139 // Create an URL from the local address, key hash and cookie
2141 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2144 pthread_mutex_unlock(&(mesh->mesh_mutex));
2148 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
2149 return meshlink_invite_ex(mesh, name, 0);
2152 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2153 if(!mesh || !invitation) {
2154 meshlink_errno = MESHLINK_EINVAL;
2158 pthread_mutex_lock(&(mesh->mesh_mutex));
2160 //Before doing meshlink_join make sure we are not connected to another mesh
2161 if(mesh->threadstarted) {
2162 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2163 meshlink_errno = MESHLINK_EINVAL;
2164 pthread_mutex_unlock(&(mesh->mesh_mutex));
2168 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2169 char copy[strlen(invitation) + 1];
2170 strcpy(copy, invitation);
2172 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2174 char *slash = strchr(copy, '/');
2182 if(strlen(slash) != 48) {
2186 char *address = copy;
2189 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2193 // Generate a throw-away key for the invitation.
2194 ecdsa_t *key = ecdsa_generate();
2197 meshlink_errno = MESHLINK_EINTERNAL;
2198 pthread_mutex_unlock(&(mesh->mesh_mutex));
2202 char *b64key = ecdsa_get_base64_public_key(key);
2206 while(address && *address) {
2207 // We allow commas in the address part to support multiple addresses in one invitation URL.
2208 comma = strchr(address, ',');
2214 // Split of the port
2215 port = strrchr(address, ':');
2223 // IPv6 address are enclosed in brackets, per RFC 3986
2224 if(*address == '[') {
2226 char *bracket = strchr(address, ']');
2239 // Connect to the meshlink daemon mentioned in the URL.
2240 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2243 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2244 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2246 if(mesh->sock == -1) {
2247 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2248 meshlink_errno = MESHLINK_ENETWORK;
2252 set_timeout(mesh->sock, 5000);
2254 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2255 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2256 meshlink_errno = MESHLINK_ENETWORK;
2257 closesocket(mesh->sock);
2265 meshlink_errno = MESHLINK_ERESOLV;
2268 if(mesh->sock != -1 || !comma) {
2275 if(mesh->sock == -1) {
2276 pthread_mutex_unlock(&mesh->mesh_mutex);
2280 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2282 // Tell him we have an invitation, and give him our throw-away key.
2286 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2287 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2288 closesocket(mesh->sock);
2289 meshlink_errno = MESHLINK_ENETWORK;
2290 pthread_mutex_unlock(&(mesh->mesh_mutex));
2296 char hisname[4096] = "";
2297 int code, hismajor, hisminor = 0;
2299 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) {
2300 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2301 closesocket(mesh->sock);
2302 meshlink_errno = MESHLINK_ENETWORK;
2303 pthread_mutex_unlock(&(mesh->mesh_mutex));
2307 // Check if the hash of the key he gave us matches the hash in the URL.
2308 char *fingerprint = mesh->line + 2;
2311 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2312 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2313 meshlink_errno = MESHLINK_EINTERNAL;
2314 pthread_mutex_unlock(&(mesh->mesh_mutex));
2318 if(memcmp(hishash, mesh->hash, 18)) {
2319 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2320 meshlink_errno = MESHLINK_EPEER;
2321 pthread_mutex_unlock(&(mesh->mesh_mutex));
2326 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2329 meshlink_errno = MESHLINK_EINTERNAL;
2330 pthread_mutex_unlock(&(mesh->mesh_mutex));
2334 // Start an SPTPS session
2335 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2336 meshlink_errno = MESHLINK_EINTERNAL;
2337 pthread_mutex_unlock(&(mesh->mesh_mutex));
2341 // Feed rest of input buffer to SPTPS
2342 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2343 meshlink_errno = MESHLINK_EPEER;
2344 pthread_mutex_unlock(&(mesh->mesh_mutex));
2350 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2352 if(errno == EINTR) {
2356 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2357 meshlink_errno = MESHLINK_ENETWORK;
2358 pthread_mutex_unlock(&(mesh->mesh_mutex));
2362 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2363 meshlink_errno = MESHLINK_EPEER;
2364 pthread_mutex_unlock(&(mesh->mesh_mutex));
2369 sptps_stop(&mesh->sptps);
2372 closesocket(mesh->sock);
2374 if(!mesh->success) {
2375 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2376 meshlink_errno = MESHLINK_EPEER;
2377 pthread_mutex_unlock(&(mesh->mesh_mutex));
2381 pthread_mutex_unlock(&(mesh->mesh_mutex));
2385 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2386 meshlink_errno = MESHLINK_EINVAL;
2387 pthread_mutex_unlock(&(mesh->mesh_mutex));
2391 char *meshlink_export(meshlink_handle_t *mesh) {
2393 meshlink_errno = MESHLINK_EINVAL;
2397 pthread_mutex_lock(&(mesh->mesh_mutex));
2399 char filename[PATH_MAX];
2400 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2401 FILE *f = fopen(filename, "r");
2404 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2405 meshlink_errno = MESHLINK_ESTORAGE;
2406 pthread_mutex_unlock(&(mesh->mesh_mutex));
2410 fseek(f, 0, SEEK_END);
2411 int fsize = ftell(f);
2414 size_t len = fsize + 9 + strlen(mesh->self->name);
2415 char *buf = xmalloc(len);
2416 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2418 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2419 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2422 meshlink_errno = MESHLINK_ESTORAGE;
2423 pthread_mutex_unlock(&(mesh->mesh_mutex));
2430 pthread_mutex_unlock(&(mesh->mesh_mutex));
2434 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2435 if(!mesh || !data) {
2436 meshlink_errno = MESHLINK_EINVAL;
2440 pthread_mutex_lock(&(mesh->mesh_mutex));
2442 if(strncmp(data, "Name = ", 7)) {
2443 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2444 meshlink_errno = MESHLINK_EPEER;
2445 pthread_mutex_unlock(&(mesh->mesh_mutex));
2449 char *end = strchr(data + 7, '\n');
2452 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2453 meshlink_errno = MESHLINK_EPEER;
2454 pthread_mutex_unlock(&(mesh->mesh_mutex));
2458 int len = end - (data + 7);
2460 memcpy(name, data + 7, len);
2463 if(!check_id(name)) {
2464 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2465 meshlink_errno = MESHLINK_EPEER;
2466 pthread_mutex_unlock(&(mesh->mesh_mutex));
2470 char filename[PATH_MAX];
2471 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2473 if(!access(filename, F_OK)) {
2474 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2475 meshlink_errno = MESHLINK_EEXIST;
2476 pthread_mutex_unlock(&(mesh->mesh_mutex));
2480 if(errno != ENOENT) {
2481 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2482 meshlink_errno = MESHLINK_ESTORAGE;
2483 pthread_mutex_unlock(&(mesh->mesh_mutex));
2487 FILE *f = fopen(filename, "w");
2490 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2491 meshlink_errno = MESHLINK_ESTORAGE;
2492 pthread_mutex_unlock(&(mesh->mesh_mutex));
2496 fwrite(end + 1, strlen(end + 1), 1, f);
2499 load_all_nodes(mesh);
2501 pthread_mutex_unlock(&(mesh->mesh_mutex));
2505 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2506 if(!mesh || !node) {
2507 meshlink_errno = MESHLINK_EINVAL;
2511 pthread_mutex_lock(&(mesh->mesh_mutex));
2515 n->status.blacklisted = true;
2516 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2518 //Make blacklisting persistent in the config file
2519 append_config_file(mesh, n->name, "blacklisted", "yes");
2521 //Immediately terminate any connections we have with the blacklisted node
2522 for list_each(connection_t, c, mesh->connections) {
2524 terminate_connection(mesh, c, c->status.active);
2528 pthread_mutex_unlock(&(mesh->mesh_mutex));
2531 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2532 if(!mesh || !node) {
2533 meshlink_errno = MESHLINK_EINVAL;
2537 pthread_mutex_lock(&(mesh->mesh_mutex));
2539 node_t *n = (node_t *)node;
2540 n->status.blacklisted = false;
2542 //TODO: remove blacklisted = yes from the config file
2544 pthread_mutex_unlock(&(mesh->mesh_mutex));
2548 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2549 mesh->default_blacklist = blacklist;
2552 /* Hint that a hostname may be found at an address
2553 * See header file for detailed comment.
2555 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2556 if(!mesh || !node || !addr) {
2560 // Ignore hints about ourself.
2561 if((node_t *)node == mesh->self) {
2565 pthread_mutex_lock(&(mesh->mesh_mutex));
2567 char *host = NULL, *port = NULL, *str = NULL;
2568 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2571 xasprintf(&str, "%s %s", host, port);
2573 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2574 modify_config_file(mesh, node->name, "Address", str, 5);
2576 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2584 pthread_mutex_unlock(&(mesh->mesh_mutex));
2585 // @TODO do we want to fire off a connection attempt right away?
2588 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2590 node_t *n = utcp->priv;
2591 meshlink_handle_t *mesh = n->mesh;
2592 return mesh->channel_accept_cb;
2595 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2596 meshlink_channel_t *channel = connection->priv;
2602 node_t *n = channel->node;
2603 meshlink_handle_t *mesh = n->mesh;
2605 if(n->status.destroyed) {
2606 meshlink_channel_close(mesh, channel);
2607 } else if(channel->receive_cb) {
2608 channel->receive_cb(mesh, channel, data, len);
2614 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2615 node_t *n = utcp_connection->utcp->priv;
2621 meshlink_handle_t *mesh = n->mesh;
2623 if(!mesh->channel_accept_cb) {
2627 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2629 channel->c = utcp_connection;
2631 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2632 utcp_accept(utcp_connection, channel_recv, channel);
2638 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2639 node_t *n = utcp->priv;
2641 if(n->status.destroyed) {
2645 meshlink_handle_t *mesh = n->mesh;
2646 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2649 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2650 if(!mesh || !channel) {
2651 meshlink_errno = MESHLINK_EINVAL;
2655 channel->receive_cb = cb;
2658 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2660 node_t *n = (node_t *)source;
2666 utcp_recv(n->utcp, data, len);
2669 static void channel_poll(struct utcp_connection *connection, size_t len) {
2670 meshlink_channel_t *channel = connection->priv;
2676 node_t *n = channel->node;
2677 meshlink_handle_t *mesh = n->mesh;
2679 if(channel->poll_cb) {
2680 channel->poll_cb(mesh, channel, len);
2684 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2686 channel->poll_cb = cb;
2687 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2690 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2692 meshlink_errno = MESHLINK_EINVAL;
2696 pthread_mutex_lock(&mesh->mesh_mutex);
2697 mesh->channel_accept_cb = cb;
2698 mesh->receive_cb = channel_receive;
2700 for splay_each(node_t, n, mesh->nodes) {
2701 if(!n->utcp && n != mesh->self) {
2702 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2706 pthread_mutex_unlock(&mesh->mesh_mutex);
2709 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) {
2711 abort(); // TODO: handle non-NULL data
2714 if(!mesh || !node) {
2715 meshlink_errno = MESHLINK_EINVAL;
2719 node_t *n = (node_t *)node;
2722 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2723 mesh->receive_cb = channel_receive;
2726 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2731 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2733 channel->receive_cb = cb;
2734 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2737 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2745 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) {
2746 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2749 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2750 if(!mesh || !channel) {
2751 meshlink_errno = MESHLINK_EINVAL;
2755 utcp_shutdown(channel->c, direction);
2758 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2759 if(!mesh || !channel) {
2760 meshlink_errno = MESHLINK_EINVAL;
2764 utcp_close(channel->c);
2768 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2769 if(!mesh || !channel) {
2770 meshlink_errno = MESHLINK_EINVAL;
2779 meshlink_errno = MESHLINK_EINVAL;
2783 // TODO: more finegrained locking.
2784 // Ideally we want to put the data into the UTCP connection's send buffer.
2785 // Then, preferrably only if there is room in the receiver window,
2786 // kick the meshlink thread to go send packets.
2788 pthread_mutex_lock(&mesh->mesh_mutex);
2789 ssize_t retval = utcp_send(channel->c, data, len);
2790 pthread_mutex_unlock(&mesh->mesh_mutex);
2793 meshlink_errno = MESHLINK_ENETWORK;
2799 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2800 if(!mesh || !channel) {
2801 meshlink_errno = MESHLINK_EINVAL;
2805 return channel->c->flags;
2808 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2809 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2810 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2813 if(mesh->node_status_cb) {
2814 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2818 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2819 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2823 n->status.duplicate = true;
2824 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2827 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2831 meshlink_errno = MESHLINK_EINVAL;
2835 pthread_mutex_lock(&mesh->mesh_mutex);
2837 if(mesh->discovery == enable) {
2841 if(mesh->threadstarted) {
2843 discovery_start(mesh);
2845 discovery_stop(mesh);
2849 mesh->discovery = enable;
2852 pthread_mutex_unlock(&mesh->mesh_mutex);
2856 meshlink_errno = MESHLINK_ENOTSUP;
2860 static void __attribute__((constructor)) meshlink_init(void) {
2863 randomize(&seed, sizeof(seed));
2867 static void __attribute__((destructor)) meshlink_exit(void) {
2871 /// Device class traits
2872 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2873 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2874 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2875 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2876 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN