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_hostname(const char *filename, char **hostname, char **port) {
100 bool canonical = false;
102 if(!filename || (*hostname && *port)) {
106 FILE *f = fopen(filename, "r");
112 while(fgets(line, sizeof(line), f)) {
118 p += strcspn(p, "\t =");
124 q = p + strspn(p, "\t ");
127 q += 1 + strspn(q + 1, "\t ");
130 // q is now pointing to the hostname
132 p = q + strcspn(q, "\t ");
138 p += strspn(p, "\t ");
139 p[strcspn(p, "\t ")] = 0;
140 // p is now pointing to the port, if present
142 if(!*port && !strcasecmp(line, "Port")) {
144 } else if(!canonical && !*hostname && !strcasecmp(line, "Address")) {
145 // Check that the hostname is a symbolic name (it's not a numeric IPv4 or IPv6 address)
146 if(!q[strspn(q, "0123456789.")] || strchr(q, ':')) {
150 *hostname = xstrdup(q);
156 } else if(!strcasecmp(line, "CanonicalAddress")) {
157 *hostname = xstrdup(q);
166 if(canonical && *hostname && *port) {
174 static bool is_valid_hostname(const char *hostname) {
179 for(const char *p = hostname; *p; p++) {
180 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
188 static bool is_valid_port(const char *port) {
195 unsigned long int result = strtoul(port, &end, 10);
196 return result && result < 65536 && !*end;
199 for(const char *p = port; *p; p++) {
200 if(!(isalnum(*p) || *p == '-')) {
208 static void set_timeout(int sock, int timeout) {
213 tv.tv_sec = timeout / 1000;
214 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
216 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
217 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
220 // Find out what local address a socket would use if we connect to the given address.
221 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
222 // of both endpoints, but this will actually not send any UDP packet.
223 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
224 struct addrinfo *rai = NULL;
225 const struct addrinfo hint = {
226 .ai_family = AF_UNSPEC,
227 .ai_socktype = SOCK_DGRAM,
228 .ai_protocol = IPPROTO_UDP,
231 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
235 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
242 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
249 struct sockaddr_storage sn;
250 socklen_t sl = sizeof(sn);
252 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
256 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
263 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
264 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
267 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
268 char *hostname = NULL;
270 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
271 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
272 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
275 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
276 if(family != AF_UNSPEC && aip->ai_family != family) {
280 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
283 set_timeout(s, 5000);
285 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
292 send(s, request, sizeof(request) - 1, 0);
293 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
298 if(line[len - 1] == '\n') {
302 char *p = strrchr(line, '\n');
305 hostname = xstrdup(p + 1);
321 // Check that the hostname is reasonable
322 if(hostname && !is_valid_hostname(hostname)) {
327 // If there is no hostname, determine the address used for an outgoing connection.
329 char localaddr[NI_MAXHOST];
330 bool success = false;
332 if(family == AF_INET) {
333 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
334 } else if(family == AF_INET6) {
335 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
339 hostname = xstrdup(localaddr);
344 meshlink_errno = MESHLINK_ERESOLV;
350 // String comparison which handles NULL arguments
351 static bool safe_streq(const char *a, const char *b) {
355 return !strcmp(a, b);
358 // This gets the hostname part for use in invitation URLs
359 static char *get_my_hostname(meshlink_handle_t *mesh) {
360 char *hostname[3] = {NULL};
361 char *port[3] = {NULL};
362 char *hostport = NULL;
364 // Use the best Address statement in our own host config file
365 char filename[PATH_MAX] = "";
366 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
367 scan_for_hostname(filename, &hostname[0], &port[0]);
369 hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET);
370 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET6);
372 // Concatenate all unique address to the hostport string
373 for (int i = 0; i < 3; i++) {
377 // Ignore duplicate hostnames
380 for (int j = 0; i < j; j++) {
381 if (safe_streq(hostname[i], hostname[j]) && safe_streq(port[i], port[j])) {
395 // Ensure we have the same addresses in our own host config file.
397 xasprintf(&tmphostport, "%s %s", hostname[i], port[i] ? port[i] : mesh->myport);
398 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
401 // Append the address to the hostport string
403 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i] ? port[i] : mesh->myport);
407 hostport = newhostport;
413 static char *get_line(const char **data) {
414 if(!data || !*data) {
423 static char line[1024];
424 const char *end = strchr(*data, '\n');
425 size_t len = end ? (size_t)(end - *data) : strlen(*data);
427 if(len >= sizeof(line)) {
428 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
432 if(len && !isprint(**data)) {
436 memcpy(line, *data, len);
448 static char *get_value(const char *data, const char *var) {
449 char *line = get_line(&data);
455 char *sep = line + strcspn(line, " \t=");
456 char *val = sep + strspn(sep, " \t");
459 val += 1 + strspn(val + 1, " \t");
464 if(strcasecmp(line, var)) {
471 static bool try_bind(int port) {
472 struct addrinfo *ai = NULL;
473 struct addrinfo hint = {
474 .ai_flags = AI_PASSIVE,
475 .ai_family = AF_UNSPEC,
476 .ai_socktype = SOCK_STREAM,
477 .ai_protocol = IPPROTO_TCP,
481 snprintf(portstr, sizeof(portstr), "%d", port);
483 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
488 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
495 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
510 int check_port(meshlink_handle_t *mesh) {
511 for(int i = 0; i < 1000; i++) {
512 int port = 0x1000 + (rand() & 0x7fff);
515 char filename[PATH_MAX];
516 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
517 FILE *f = fopen(filename, "a");
520 meshlink_errno = MESHLINK_ESTORAGE;
521 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
525 fprintf(f, "Port = %d\n", port);
531 meshlink_errno = MESHLINK_ENETWORK;
532 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
536 static void deltree(const char *dirname) {
537 DIR *d = opendir(dirname);
542 while((ent = readdir(d))) {
543 if(ent->d_name[0] == '.') {
547 char filename[PATH_MAX];
548 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
550 if(unlink(filename)) {
561 static bool finalize_join(meshlink_handle_t *mesh) {
562 char *name = xstrdup(get_value(mesh->data, "Name"));
565 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
569 if(!check_id(name)) {
570 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
574 char filename[PATH_MAX];
575 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
577 FILE *f = fopen(filename, "w");
580 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
584 fprintf(f, "Name = %s\n", name);
586 // Wipe all old host config files and invitations
587 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
590 if(mkdir(filename, 0777) && errno != EEXIST) {
591 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
595 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
598 // Create a new host config file for ourself
599 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
600 FILE *fh = fopen(filename, "w");
603 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
608 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
609 // Other chunks go unfiltered to their respective host config files
610 const char *p = mesh->data;
613 while((l = get_line(&p))) {
619 // Split line into variable and value
620 int len = strcspn(l, "\t =");
622 value += strspn(value, "\t ");
626 value += strspn(value, "\t ");
632 if(!strcasecmp(l, "Name"))
633 if(strcmp(value, name)) {
637 } else if(!strcasecmp(l, "NetName")) {
641 // Check the list of known variables
645 for(i = 0; variables[i].name; i++) {
646 if(strcasecmp(l, variables[i].name)) {
654 // Ignore unknown and unsafe variables
656 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
658 } else if(!(variables[i].type & VAR_SAFE)) {
659 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
663 // Copy the safe variable to the right config file
664 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
669 while(l && !strcasecmp(l, "Name")) {
670 if(!check_id(value)) {
671 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
675 if(!strcmp(value, name)) {
676 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
680 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
681 f = fopen(filename, "w");
684 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
688 while((l = get_line(&p))) {
689 if(!strcmp(l, "#---------------------------------------------------------------#")) {
693 int len = strcspn(l, "\t =");
695 if(len == 4 && !strncasecmp(l, "Name", 4)) {
697 value += strspn(value, "\t ");
701 value += strspn(value, "\t ");
715 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
722 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
723 fprintf(fh, "Port = %s\n", mesh->myport);
727 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
731 free(mesh->self->name);
732 free(mesh->self->connection->name);
733 mesh->name = xstrdup(name);
734 mesh->self->name = xstrdup(name);
735 mesh->self->connection->name = name;
737 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
739 load_all_nodes(mesh);
744 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
746 meshlink_handle_t *mesh = handle;
747 const char *ptr = data;
750 int result = send(mesh->sock, ptr, len, 0);
752 if(result == -1 && errno == EINTR) {
754 } else if(result <= 0) {
765 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
766 meshlink_handle_t *mesh = handle;
769 case SPTPS_HANDSHAKE:
770 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
773 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
774 memcpy(mesh->data + mesh->thedatalen, msg, len);
775 mesh->thedatalen += len;
776 mesh->data[mesh->thedatalen] = 0;
780 mesh->thedatalen = 0;
781 return finalize_join(mesh);
784 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
785 shutdown(mesh->sock, SHUT_RDWR);
786 mesh->success = true;
796 static bool recvline(meshlink_handle_t *mesh, size_t len) {
797 char *newline = NULL;
803 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
804 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
806 if(result == -1 && errno == EINTR) {
808 } else if(result <= 0) {
812 mesh->blen += result;
815 if((size_t)(newline - mesh->buffer) >= len) {
819 len = newline - mesh->buffer;
821 memcpy(mesh->line, mesh->buffer, len);
823 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
824 mesh->blen -= len + 1;
828 static bool sendline(int fd, char *format, ...) {
829 static char buffer[4096];
834 va_start(ap, format);
835 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
838 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
846 int result = send(fd, p, blen, MSG_NOSIGNAL);
848 if(result == -1 && errno == EINTR) {
850 } else if(result <= 0) {
861 static const char *errstr[] = {
862 [MESHLINK_OK] = "No error",
863 [MESHLINK_EINVAL] = "Invalid argument",
864 [MESHLINK_ENOMEM] = "Out of memory",
865 [MESHLINK_ENOENT] = "No such node",
866 [MESHLINK_EEXIST] = "Node already exists",
867 [MESHLINK_EINTERNAL] = "Internal error",
868 [MESHLINK_ERESOLV] = "Could not resolve hostname",
869 [MESHLINK_ESTORAGE] = "Storage error",
870 [MESHLINK_ENETWORK] = "Network error",
871 [MESHLINK_EPEER] = "Error communicating with peer",
872 [MESHLINK_ENOTSUP] = "Operation not supported",
873 [MESHLINK_EBUSY] = "MeshLink instance already in use",
876 const char *meshlink_strerror(meshlink_errno_t err) {
877 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
878 return "Invalid error code";
884 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
887 char pubname[PATH_MAX], privname[PATH_MAX];
889 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
891 if(!(key = ecdsa_generate())) {
892 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
893 meshlink_errno = MESHLINK_EINTERNAL;
896 logger(mesh, MESHLINK_DEBUG, "Done.\n");
899 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
900 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
901 meshlink_errno = MESHLINK_ESTORAGE;
905 f = fopen(privname, "wb");
908 meshlink_errno = MESHLINK_ESTORAGE;
913 fchmod(fileno(f), 0600);
916 if(!ecdsa_write_pem_private_key(key, f)) {
917 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
920 meshlink_errno = MESHLINK_EINTERNAL;
926 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
927 f = fopen(pubname, "a");
930 meshlink_errno = MESHLINK_ESTORAGE;
934 char *pubkey = ecdsa_get_base64_public_key(key);
935 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
944 static struct timeval idle(event_loop_t *loop, void *data) {
946 meshlink_handle_t *mesh = data;
947 struct timeval t, tmin = {3600, 0};
949 for splay_each(node_t, n, mesh->nodes) {
954 t = utcp_timeout(n->utcp);
956 if(timercmp(&t, &tmin, <)) {
964 // Get our local address(es) by simulating connecting to an Internet host.
965 static void add_local_addresses(meshlink_handle_t *mesh) {
966 char host[NI_MAXHOST];
967 char entry[MAX_STRING_SIZE];
971 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
972 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
973 append_config_file(mesh, mesh->name, "Address", entry);
978 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
979 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
980 append_config_file(mesh, mesh->name, "Address", entry);
984 static bool meshlink_setup(meshlink_handle_t *mesh) {
985 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
986 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
987 meshlink_errno = MESHLINK_ESTORAGE;
991 char filename[PATH_MAX];
992 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
994 if(mkdir(filename, 0777) && errno != EEXIST) {
995 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
996 meshlink_errno = MESHLINK_ESTORAGE;
1000 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1002 if(!access(filename, F_OK)) {
1003 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1004 meshlink_errno = MESHLINK_EEXIST;
1008 FILE *f = fopen(filename, "w");
1011 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1012 meshlink_errno = MESHLINK_ESTORAGE;
1016 fprintf(f, "Name = %s\n", mesh->name);
1019 if(!ecdsa_keygen(mesh)) {
1020 meshlink_errno = MESHLINK_EINTERNAL;
1025 if(check_port(mesh) == 0) {
1026 meshlink_errno = MESHLINK_ENETWORK;
1034 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1035 // Validate arguments provided by the application
1036 bool usingname = false;
1038 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1040 if(!confbase || !*confbase) {
1041 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1042 meshlink_errno = MESHLINK_EINVAL;
1046 if(!appname || !*appname) {
1047 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1048 meshlink_errno = MESHLINK_EINVAL;
1052 if(strchr(appname, ' ')) {
1053 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1054 meshlink_errno = MESHLINK_EINVAL;
1058 if(!name || !*name) {
1059 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1061 } else { //check name only if there is a name != NULL
1063 if(!check_id(name)) {
1064 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1065 meshlink_errno = MESHLINK_EINVAL;
1072 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1073 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1074 meshlink_errno = MESHLINK_EINVAL;
1078 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1079 mesh->confbase = xstrdup(confbase);
1080 mesh->appname = xstrdup(appname);
1081 mesh->devclass = devclass;
1082 mesh->discovery = true;
1083 mesh->invitation_timeout = 604800; // 1 week
1086 mesh->name = xstrdup(name);
1090 pthread_mutexattr_t attr;
1091 pthread_mutexattr_init(&attr);
1092 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1093 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1095 mesh->threadstarted = false;
1096 event_loop_init(&mesh->loop);
1097 mesh->loop.data = mesh;
1099 meshlink_queue_init(&mesh->outpacketqueue);
1101 // Check whether meshlink.conf already exists
1103 char filename[PATH_MAX];
1104 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1106 if(access(filename, R_OK)) {
1107 if(errno == ENOENT) {
1108 // If not, create it
1109 if(!meshlink_setup(mesh)) {
1110 // meshlink_errno is set by meshlink_setup()
1114 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1115 meshlink_close(mesh);
1116 meshlink_errno = MESHLINK_ESTORAGE;
1121 // Open the configuration file and lock it
1123 mesh->conffile = fopen(filename, "r");
1125 if(!mesh->conffile) {
1126 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1127 meshlink_close(mesh);
1128 meshlink_errno = MESHLINK_ESTORAGE;
1133 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1137 // TODO: use _locking()?
1139 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1140 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1141 meshlink_close(mesh);
1142 meshlink_errno = MESHLINK_EBUSY;
1147 // Read the configuration
1149 init_configuration(&mesh->config);
1151 if(!read_server_config(mesh)) {
1152 meshlink_close(mesh);
1153 meshlink_errno = MESHLINK_ESTORAGE;
1158 struct WSAData wsa_state;
1160 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1164 // Setup up everything
1165 // TODO: we should not open listening sockets yet
1167 if(!setup_network(mesh)) {
1168 meshlink_close(mesh);
1169 meshlink_errno = MESHLINK_ENETWORK;
1173 add_local_addresses(mesh);
1175 idle_set(&mesh->loop, idle, mesh);
1177 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1181 static void *meshlink_main_loop(void *arg) {
1182 meshlink_handle_t *mesh = arg;
1184 pthread_mutex_lock(&(mesh->mesh_mutex));
1186 try_outgoing_connections(mesh);
1188 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1190 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1192 pthread_mutex_unlock(&(mesh->mesh_mutex));
1196 bool meshlink_start(meshlink_handle_t *mesh) {
1198 meshlink_errno = MESHLINK_EINVAL;
1202 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1204 pthread_mutex_lock(&(mesh->mesh_mutex));
1206 if(mesh->threadstarted) {
1207 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1208 pthread_mutex_unlock(&(mesh->mesh_mutex));
1212 if(mesh->listen_socket[0].tcp.fd < 0) {
1213 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1214 meshlink_errno = MESHLINK_ENETWORK;
1218 mesh->thedatalen = 0;
1220 // TODO: open listening sockets first
1222 //Check that a valid name is set
1224 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1225 meshlink_errno = MESHLINK_EINVAL;
1226 pthread_mutex_unlock(&(mesh->mesh_mutex));
1230 // Start the main thread
1232 event_loop_start(&mesh->loop);
1234 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1235 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1236 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1237 meshlink_errno = MESHLINK_EINTERNAL;
1238 event_loop_stop(&mesh->loop);
1239 pthread_mutex_unlock(&(mesh->mesh_mutex));
1243 mesh->threadstarted = true;
1247 if(mesh->discovery) {
1248 discovery_start(mesh);
1253 pthread_mutex_unlock(&(mesh->mesh_mutex));
1257 void meshlink_stop(meshlink_handle_t *mesh) {
1259 meshlink_errno = MESHLINK_EINVAL;
1263 pthread_mutex_lock(&(mesh->mesh_mutex));
1264 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1269 if(mesh->discovery) {
1270 discovery_stop(mesh);
1275 // Shut down the main thread
1276 event_loop_stop(&mesh->loop);
1278 // Send ourselves a UDP packet to kick the event loop
1279 for(int i = 0; i < mesh->listen_sockets; i++) {
1281 socklen_t salen = sizeof(sa.sa);
1283 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1284 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1288 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1289 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1293 if(mesh->threadstarted) {
1294 // Wait for the main thread to finish
1295 pthread_mutex_unlock(&(mesh->mesh_mutex));
1296 pthread_join(mesh->thread, NULL);
1297 pthread_mutex_lock(&(mesh->mesh_mutex));
1299 mesh->threadstarted = false;
1302 // Close all metaconnections
1303 if(mesh->connections) {
1304 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1306 connection_t *c = node->data;
1308 terminate_connection(mesh, c, false);
1312 if(mesh->outgoings) {
1313 list_delete_list(mesh->outgoings);
1314 mesh->outgoings = NULL;
1317 pthread_mutex_unlock(&(mesh->mesh_mutex));
1320 void meshlink_close(meshlink_handle_t *mesh) {
1321 if(!mesh || !mesh->confbase) {
1322 meshlink_errno = MESHLINK_EINVAL;
1326 // stop can be called even if mesh has not been started
1327 meshlink_stop(mesh);
1329 // lock is not released after this
1330 pthread_mutex_lock(&(mesh->mesh_mutex));
1332 // Close and free all resources used.
1334 close_network_connections(mesh);
1336 logger(mesh, MESHLINK_INFO, "Terminating");
1338 exit_configuration(&mesh->config);
1339 event_loop_exit(&mesh->loop);
1343 if(mesh->confbase) {
1349 ecdsa_free(mesh->invitation_key);
1352 free(mesh->appname);
1353 free(mesh->confbase);
1354 pthread_mutex_destroy(&(mesh->mesh_mutex));
1356 if(mesh->conffile) {
1357 fclose(mesh->conffile);
1360 memset(mesh, 0, sizeof(*mesh));
1365 bool meshlink_destroy(const char *confbase) {
1367 meshlink_errno = MESHLINK_EINVAL;
1371 char filename[PATH_MAX];
1372 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1374 if(unlink(filename)) {
1375 if(errno == ENOENT) {
1376 meshlink_errno = MESHLINK_ENOENT;
1379 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1380 meshlink_errno = MESHLINK_ESTORAGE;
1390 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1392 meshlink_errno = MESHLINK_EINVAL;
1396 pthread_mutex_lock(&(mesh->mesh_mutex));
1397 mesh->receive_cb = cb;
1398 pthread_mutex_unlock(&(mesh->mesh_mutex));
1401 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1403 meshlink_errno = MESHLINK_EINVAL;
1407 pthread_mutex_lock(&(mesh->mesh_mutex));
1408 mesh->node_status_cb = cb;
1409 pthread_mutex_unlock(&(mesh->mesh_mutex));
1412 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1414 meshlink_errno = MESHLINK_EINVAL;
1418 pthread_mutex_lock(&(mesh->mesh_mutex));
1419 mesh->node_duplicate_cb = cb;
1420 pthread_mutex_unlock(&(mesh->mesh_mutex));
1423 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1425 pthread_mutex_lock(&(mesh->mesh_mutex));
1427 mesh->log_level = cb ? level : 0;
1428 pthread_mutex_unlock(&(mesh->mesh_mutex));
1431 global_log_level = cb ? level : 0;
1435 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1436 meshlink_packethdr_t *hdr;
1438 // Validate arguments
1439 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1440 meshlink_errno = MESHLINK_EINVAL;
1449 meshlink_errno = MESHLINK_EINVAL;
1453 // Prepare the packet
1454 vpn_packet_t *packet = malloc(sizeof(*packet));
1457 meshlink_errno = MESHLINK_ENOMEM;
1461 packet->probe = false;
1462 packet->tcp = false;
1463 packet->len = len + sizeof(*hdr);
1465 hdr = (meshlink_packethdr_t *)packet->data;
1466 memset(hdr, 0, sizeof(*hdr));
1467 // leave the last byte as 0 to make sure strings are always
1468 // null-terminated if they are longer than the buffer
1469 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1470 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1472 memcpy(packet->data + sizeof(*hdr), data, len);
1475 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1477 meshlink_errno = MESHLINK_ENOMEM;
1481 // Notify event loop
1482 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1487 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1489 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1495 mesh->self->in_packets++;
1496 mesh->self->in_bytes += packet->len;
1497 route(mesh, mesh->self, packet);
1500 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1501 if(!mesh || !destination) {
1502 meshlink_errno = MESHLINK_EINVAL;
1506 pthread_mutex_lock(&(mesh->mesh_mutex));
1508 node_t *n = (node_t *)destination;
1510 if(!n->status.reachable) {
1511 pthread_mutex_unlock(&(mesh->mesh_mutex));
1514 } else if(n->mtuprobes > 30 && n->minmtu) {
1515 pthread_mutex_unlock(&(mesh->mesh_mutex));
1518 pthread_mutex_unlock(&(mesh->mesh_mutex));
1523 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1524 if(!mesh || !node) {
1525 meshlink_errno = MESHLINK_EINVAL;
1529 pthread_mutex_lock(&(mesh->mesh_mutex));
1531 node_t *n = (node_t *)node;
1533 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1534 meshlink_errno = MESHLINK_EINTERNAL;
1535 pthread_mutex_unlock(&(mesh->mesh_mutex));
1539 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1542 meshlink_errno = MESHLINK_EINTERNAL;
1545 pthread_mutex_unlock(&(mesh->mesh_mutex));
1549 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1551 meshlink_errno = MESHLINK_EINVAL;
1555 return (meshlink_node_t *)mesh->self;
1558 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1559 if(!mesh || !name) {
1560 meshlink_errno = MESHLINK_EINVAL;
1564 meshlink_node_t *node = NULL;
1566 pthread_mutex_lock(&(mesh->mesh_mutex));
1567 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1568 pthread_mutex_unlock(&(mesh->mesh_mutex));
1572 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1573 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1574 meshlink_errno = MESHLINK_EINVAL;
1578 meshlink_node_t **result;
1581 pthread_mutex_lock(&(mesh->mesh_mutex));
1583 *nmemb = mesh->nodes->count;
1584 result = realloc(nodes, *nmemb * sizeof(*nodes));
1587 meshlink_node_t **p = result;
1589 for splay_each(node_t, n, mesh->nodes) {
1590 *p++ = (meshlink_node_t *)n;
1595 meshlink_errno = MESHLINK_ENOMEM;
1598 pthread_mutex_unlock(&(mesh->mesh_mutex));
1603 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1604 if(!mesh || !data || !len || !signature || !siglen) {
1605 meshlink_errno = MESHLINK_EINVAL;
1609 if(*siglen < MESHLINK_SIGLEN) {
1610 meshlink_errno = MESHLINK_EINVAL;
1614 pthread_mutex_lock(&(mesh->mesh_mutex));
1616 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1617 meshlink_errno = MESHLINK_EINTERNAL;
1618 pthread_mutex_unlock(&(mesh->mesh_mutex));
1622 *siglen = MESHLINK_SIGLEN;
1623 pthread_mutex_unlock(&(mesh->mesh_mutex));
1627 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1628 if(!mesh || !data || !len || !signature) {
1629 meshlink_errno = MESHLINK_EINVAL;
1633 if(siglen != MESHLINK_SIGLEN) {
1634 meshlink_errno = MESHLINK_EINVAL;
1638 pthread_mutex_lock(&(mesh->mesh_mutex));
1642 struct node_t *n = (struct node_t *)source;
1643 node_read_ecdsa_public_key(mesh, n);
1646 meshlink_errno = MESHLINK_EINTERNAL;
1649 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1652 pthread_mutex_unlock(&(mesh->mesh_mutex));
1656 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1657 char filename[PATH_MAX];
1659 pthread_mutex_lock(&(mesh->mesh_mutex));
1661 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1663 if(mkdir(filename, 0700) && errno != EEXIST) {
1664 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1665 meshlink_errno = MESHLINK_ESTORAGE;
1666 pthread_mutex_unlock(&(mesh->mesh_mutex));
1670 // Count the number of valid invitations, clean up old ones
1671 DIR *dir = opendir(filename);
1674 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1675 meshlink_errno = MESHLINK_ESTORAGE;
1676 pthread_mutex_unlock(&(mesh->mesh_mutex));
1683 time_t deadline = time(NULL) - 604800; // 1 week in the past
1685 while((ent = readdir(dir))) {
1686 if(strlen(ent->d_name) != 24) {
1690 char invname[PATH_MAX];
1693 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1694 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1698 if(!stat(invname, &st)) {
1699 if(mesh->invitation_key && deadline < st.st_mtime) {
1705 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1711 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1713 meshlink_errno = MESHLINK_ESTORAGE;
1714 pthread_mutex_unlock(&(mesh->mesh_mutex));
1720 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1722 // Remove the key if there are no outstanding invitations.
1726 if(mesh->invitation_key) {
1727 ecdsa_free(mesh->invitation_key);
1728 mesh->invitation_key = NULL;
1732 if(mesh->invitation_key) {
1733 pthread_mutex_unlock(&(mesh->mesh_mutex));
1737 // Create a new key if necessary.
1738 FILE *f = fopen(filename, "rb");
1741 if(errno != ENOENT) {
1742 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1743 meshlink_errno = MESHLINK_ESTORAGE;
1744 pthread_mutex_unlock(&(mesh->mesh_mutex));
1748 mesh->invitation_key = ecdsa_generate();
1750 if(!mesh->invitation_key) {
1751 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1752 meshlink_errno = MESHLINK_EINTERNAL;
1753 pthread_mutex_unlock(&(mesh->mesh_mutex));
1757 f = fopen(filename, "wb");
1760 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1761 meshlink_errno = MESHLINK_ESTORAGE;
1762 pthread_mutex_unlock(&(mesh->mesh_mutex));
1766 chmod(filename, 0600);
1767 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1770 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1773 if(!mesh->invitation_key) {
1774 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1775 meshlink_errno = MESHLINK_ESTORAGE;
1779 pthread_mutex_unlock(&(mesh->mesh_mutex));
1780 return mesh->invitation_key;
1783 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1784 if(!mesh || !node || !address) {
1785 meshlink_errno = MESHLINK_EINVAL;
1789 if(!is_valid_hostname(address)) {
1790 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1791 meshlink_errno = MESHLINK_EINVAL;
1795 if(port && !is_valid_port(port)) {
1796 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1797 meshlink_errno = MESHLINK_EINVAL;
1801 char *canonical_address;
1804 xasprintf(&canonical_address, "%s %s", address, port);
1806 canonical_address = xstrdup(address);
1809 pthread_mutex_lock(&(mesh->mesh_mutex));
1810 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1811 pthread_mutex_unlock(&(mesh->mesh_mutex));
1813 free(canonical_address);
1817 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1818 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1821 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1823 meshlink_errno = MESHLINK_EINVAL;
1827 char *address = meshlink_get_external_address(mesh);
1835 pthread_mutex_lock(&(mesh->mesh_mutex));
1836 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1837 pthread_mutex_unlock(&(mesh->mesh_mutex));
1843 int meshlink_get_port(meshlink_handle_t *mesh) {
1845 meshlink_errno = MESHLINK_EINVAL;
1850 meshlink_errno = MESHLINK_EINTERNAL;
1854 return atoi(mesh->myport);
1857 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1858 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1859 meshlink_errno = MESHLINK_EINVAL;
1863 if(mesh->myport && port == atoi(mesh->myport)) {
1867 if(!try_bind(port)) {
1868 meshlink_errno = MESHLINK_ENETWORK;
1874 pthread_mutex_lock(&(mesh->mesh_mutex));
1876 if(mesh->threadstarted) {
1877 meshlink_errno = MESHLINK_EINVAL;
1881 close_network_connections(mesh);
1882 exit_configuration(&mesh->config);
1885 snprintf(portstr, sizeof(portstr), "%d", port);
1886 portstr[sizeof(portstr) - 1] = 0;
1888 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1890 init_configuration(&mesh->config);
1892 if(!read_server_config(mesh)) {
1893 meshlink_errno = MESHLINK_ESTORAGE;
1894 } else if(!setup_network(mesh)) {
1895 meshlink_errno = MESHLINK_ENETWORK;
1901 pthread_mutex_unlock(&(mesh->mesh_mutex));
1906 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1907 mesh->invitation_timeout = timeout;
1910 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1912 meshlink_errno = MESHLINK_EINVAL;
1916 pthread_mutex_lock(&(mesh->mesh_mutex));
1918 // Check validity of the new node's name
1919 if(!check_id(name)) {
1920 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1921 meshlink_errno = MESHLINK_EINVAL;
1922 pthread_mutex_unlock(&(mesh->mesh_mutex));
1926 // Ensure no host configuration file with that name exists
1927 char filename[PATH_MAX];
1928 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1930 if(!access(filename, F_OK)) {
1931 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1932 meshlink_errno = MESHLINK_EEXIST;
1933 pthread_mutex_unlock(&(mesh->mesh_mutex));
1937 // Ensure no other nodes know about this name
1938 if(meshlink_get_node(mesh, name)) {
1939 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1940 meshlink_errno = MESHLINK_EEXIST;
1941 pthread_mutex_unlock(&(mesh->mesh_mutex));
1945 // Get the local address
1946 char *address = get_my_hostname(mesh);
1949 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1950 meshlink_errno = MESHLINK_ERESOLV;
1951 pthread_mutex_unlock(&(mesh->mesh_mutex));
1955 if(!refresh_invitation_key(mesh)) {
1956 meshlink_errno = MESHLINK_EINTERNAL;
1957 pthread_mutex_unlock(&(mesh->mesh_mutex));
1963 // Create a hash of the key.
1964 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1965 sha512(fingerprint, strlen(fingerprint), hash);
1966 b64encode_urlsafe(hash, hash, 18);
1968 // Create a random cookie for this invitation.
1970 randomize(cookie, 18);
1972 // Create a filename that doesn't reveal the cookie itself
1973 char buf[18 + strlen(fingerprint)];
1974 char cookiehash[64];
1975 memcpy(buf, cookie, 18);
1976 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1977 sha512(buf, sizeof(buf), cookiehash);
1978 b64encode_urlsafe(cookiehash, cookiehash, 18);
1980 b64encode_urlsafe(cookie, cookie, 18);
1984 // Create a file containing the details of the invitation.
1985 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1986 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1989 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1990 meshlink_errno = MESHLINK_ESTORAGE;
1991 pthread_mutex_unlock(&(mesh->mesh_mutex));
1995 FILE *f = fdopen(ifd, "w");
2001 // Fill in the details.
2002 fprintf(f, "Name = %s\n", name);
2003 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2005 // Copy Broadcast and Mode
2006 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2007 FILE *tc = fopen(filename, "r");
2012 while(fgets(buf, sizeof(buf), tc)) {
2013 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2014 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2017 // Make sure there is a newline character.
2018 if(!strchr(buf, '\n')) {
2026 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2027 meshlink_errno = MESHLINK_ESTORAGE;
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2032 fprintf(f, "#---------------------------------------------------------------#\n");
2033 fprintf(f, "Name = %s\n", mesh->self->name);
2035 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2039 // Create an URL from the local address, key hash and cookie
2041 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2044 pthread_mutex_unlock(&(mesh->mesh_mutex));
2048 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2049 if(!mesh || !invitation) {
2050 meshlink_errno = MESHLINK_EINVAL;
2054 pthread_mutex_lock(&(mesh->mesh_mutex));
2056 //Before doing meshlink_join make sure we are not connected to another mesh
2057 if(mesh->threadstarted) {
2058 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2059 meshlink_errno = MESHLINK_EINVAL;
2060 pthread_mutex_unlock(&(mesh->mesh_mutex));
2064 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2065 char copy[strlen(invitation) + 1];
2066 strcpy(copy, invitation);
2068 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2070 char *slash = strchr(copy, '/');
2078 if(strlen(slash) != 48) {
2082 char *address = copy;
2085 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2089 // Generate a throw-away key for the invitation.
2090 ecdsa_t *key = ecdsa_generate();
2093 meshlink_errno = MESHLINK_EINTERNAL;
2094 pthread_mutex_unlock(&(mesh->mesh_mutex));
2098 char *b64key = ecdsa_get_base64_public_key(key);
2102 while(address && *address) {
2103 // We allow commas in the address part to support multiple addresses in one invitation URL.
2104 comma = strchr(address, ',');
2110 // Split of the port
2111 port = strrchr(address, ':');
2119 // IPv6 address are enclosed in brackets, per RFC 3986
2120 if(*address == '[') {
2122 char *bracket = strchr(address, ']');
2135 // Connect to the meshlink daemon mentioned in the URL.
2136 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2139 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2140 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2142 if(mesh->sock == -1) {
2143 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2144 meshlink_errno = MESHLINK_ENETWORK;
2148 set_timeout(mesh->sock, 5000);
2150 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2151 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2152 meshlink_errno = MESHLINK_ENETWORK;
2153 closesocket(mesh->sock);
2161 meshlink_errno = MESHLINK_ERESOLV;
2164 if(mesh->sock != -1 || !comma) {
2171 if(mesh->sock == -1) {
2172 pthread_mutex_unlock(&mesh->mesh_mutex);
2176 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2178 // Tell him we have an invitation, and give him our throw-away key.
2182 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2183 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2184 closesocket(mesh->sock);
2185 meshlink_errno = MESHLINK_ENETWORK;
2186 pthread_mutex_unlock(&(mesh->mesh_mutex));
2192 char hisname[4096] = "";
2193 int code, hismajor, hisminor = 0;
2195 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) {
2196 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2197 closesocket(mesh->sock);
2198 meshlink_errno = MESHLINK_ENETWORK;
2199 pthread_mutex_unlock(&(mesh->mesh_mutex));
2203 // Check if the hash of the key he gave us matches the hash in the URL.
2204 char *fingerprint = mesh->line + 2;
2207 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2208 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2209 meshlink_errno = MESHLINK_EINTERNAL;
2210 pthread_mutex_unlock(&(mesh->mesh_mutex));
2214 if(memcmp(hishash, mesh->hash, 18)) {
2215 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2216 meshlink_errno = MESHLINK_EPEER;
2217 pthread_mutex_unlock(&(mesh->mesh_mutex));
2222 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2225 meshlink_errno = MESHLINK_EINTERNAL;
2226 pthread_mutex_unlock(&(mesh->mesh_mutex));
2230 // Start an SPTPS session
2231 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2232 meshlink_errno = MESHLINK_EINTERNAL;
2233 pthread_mutex_unlock(&(mesh->mesh_mutex));
2237 // Feed rest of input buffer to SPTPS
2238 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2239 meshlink_errno = MESHLINK_EPEER;
2240 pthread_mutex_unlock(&(mesh->mesh_mutex));
2246 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2248 if(errno == EINTR) {
2252 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2253 meshlink_errno = MESHLINK_ENETWORK;
2254 pthread_mutex_unlock(&(mesh->mesh_mutex));
2258 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2259 meshlink_errno = MESHLINK_EPEER;
2260 pthread_mutex_unlock(&(mesh->mesh_mutex));
2265 sptps_stop(&mesh->sptps);
2268 closesocket(mesh->sock);
2270 if(!mesh->success) {
2271 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2272 meshlink_errno = MESHLINK_EPEER;
2273 pthread_mutex_unlock(&(mesh->mesh_mutex));
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2281 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2282 meshlink_errno = MESHLINK_EINVAL;
2283 pthread_mutex_unlock(&(mesh->mesh_mutex));
2287 char *meshlink_export(meshlink_handle_t *mesh) {
2289 meshlink_errno = MESHLINK_EINVAL;
2293 pthread_mutex_lock(&(mesh->mesh_mutex));
2295 char filename[PATH_MAX];
2296 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2297 FILE *f = fopen(filename, "r");
2300 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2301 meshlink_errno = MESHLINK_ESTORAGE;
2302 pthread_mutex_unlock(&(mesh->mesh_mutex));
2306 fseek(f, 0, SEEK_END);
2307 int fsize = ftell(f);
2310 size_t len = fsize + 9 + strlen(mesh->self->name);
2311 char *buf = xmalloc(len);
2312 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2314 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2315 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2318 meshlink_errno = MESHLINK_ESTORAGE;
2319 pthread_mutex_unlock(&(mesh->mesh_mutex));
2326 pthread_mutex_unlock(&(mesh->mesh_mutex));
2330 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2331 if(!mesh || !data) {
2332 meshlink_errno = MESHLINK_EINVAL;
2336 pthread_mutex_lock(&(mesh->mesh_mutex));
2338 if(strncmp(data, "Name = ", 7)) {
2339 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2340 meshlink_errno = MESHLINK_EPEER;
2341 pthread_mutex_unlock(&(mesh->mesh_mutex));
2345 char *end = strchr(data + 7, '\n');
2348 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2349 meshlink_errno = MESHLINK_EPEER;
2350 pthread_mutex_unlock(&(mesh->mesh_mutex));
2354 int len = end - (data + 7);
2356 memcpy(name, data + 7, len);
2359 if(!check_id(name)) {
2360 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2361 meshlink_errno = MESHLINK_EPEER;
2362 pthread_mutex_unlock(&(mesh->mesh_mutex));
2366 char filename[PATH_MAX];
2367 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2369 if(!access(filename, F_OK)) {
2370 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2371 meshlink_errno = MESHLINK_EEXIST;
2372 pthread_mutex_unlock(&(mesh->mesh_mutex));
2376 if(errno != ENOENT) {
2377 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2378 meshlink_errno = MESHLINK_ESTORAGE;
2379 pthread_mutex_unlock(&(mesh->mesh_mutex));
2383 FILE *f = fopen(filename, "w");
2386 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2387 meshlink_errno = MESHLINK_ESTORAGE;
2388 pthread_mutex_unlock(&(mesh->mesh_mutex));
2392 fwrite(end + 1, strlen(end + 1), 1, f);
2395 load_all_nodes(mesh);
2397 pthread_mutex_unlock(&(mesh->mesh_mutex));
2401 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2402 if(!mesh || !node) {
2403 meshlink_errno = MESHLINK_EINVAL;
2407 pthread_mutex_lock(&(mesh->mesh_mutex));
2411 n->status.blacklisted = true;
2412 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2414 //Make blacklisting persistent in the config file
2415 append_config_file(mesh, n->name, "blacklisted", "yes");
2417 //Immediately terminate any connections we have with the blacklisted node
2418 for list_each(connection_t, c, mesh->connections) {
2420 terminate_connection(mesh, c, c->status.active);
2424 pthread_mutex_unlock(&(mesh->mesh_mutex));
2427 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2428 if(!mesh || !node) {
2429 meshlink_errno = MESHLINK_EINVAL;
2433 pthread_mutex_lock(&(mesh->mesh_mutex));
2435 node_t *n = (node_t *)node;
2436 n->status.blacklisted = false;
2438 //TODO: remove blacklisted = yes from the config file
2440 pthread_mutex_unlock(&(mesh->mesh_mutex));
2444 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2445 mesh->default_blacklist = blacklist;
2448 /* Hint that a hostname may be found at an address
2449 * See header file for detailed comment.
2451 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2452 if(!mesh || !node || !addr) {
2456 // Ignore hints about ourself.
2457 if((node_t *)node == mesh->self) {
2461 pthread_mutex_lock(&(mesh->mesh_mutex));
2463 char *host = NULL, *port = NULL, *str = NULL;
2464 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2467 xasprintf(&str, "%s %s", host, port);
2469 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2470 modify_config_file(mesh, node->name, "Address", str, 5);
2472 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2480 pthread_mutex_unlock(&(mesh->mesh_mutex));
2481 // @TODO do we want to fire off a connection attempt right away?
2484 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2486 node_t *n = utcp->priv;
2487 meshlink_handle_t *mesh = n->mesh;
2488 return mesh->channel_accept_cb;
2491 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2492 meshlink_channel_t *channel = connection->priv;
2498 node_t *n = channel->node;
2499 meshlink_handle_t *mesh = n->mesh;
2501 if(n->status.destroyed) {
2502 meshlink_channel_close(mesh, channel);
2503 } else if(channel->receive_cb) {
2504 channel->receive_cb(mesh, channel, data, len);
2510 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2511 node_t *n = utcp_connection->utcp->priv;
2517 meshlink_handle_t *mesh = n->mesh;
2519 if(!mesh->channel_accept_cb) {
2523 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2525 channel->c = utcp_connection;
2527 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2528 utcp_accept(utcp_connection, channel_recv, channel);
2534 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2535 node_t *n = utcp->priv;
2537 if(n->status.destroyed) {
2541 meshlink_handle_t *mesh = n->mesh;
2542 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2545 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2546 if(!mesh || !channel) {
2547 meshlink_errno = MESHLINK_EINVAL;
2551 channel->receive_cb = cb;
2554 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2556 node_t *n = (node_t *)source;
2562 utcp_recv(n->utcp, data, len);
2565 static void channel_poll(struct utcp_connection *connection, size_t len) {
2566 meshlink_channel_t *channel = connection->priv;
2572 node_t *n = channel->node;
2573 meshlink_handle_t *mesh = n->mesh;
2575 if(channel->poll_cb) {
2576 channel->poll_cb(mesh, channel, len);
2580 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2582 channel->poll_cb = cb;
2583 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2586 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2588 meshlink_errno = MESHLINK_EINVAL;
2592 pthread_mutex_lock(&mesh->mesh_mutex);
2593 mesh->channel_accept_cb = cb;
2594 mesh->receive_cb = channel_receive;
2596 for splay_each(node_t, n, mesh->nodes) {
2597 if(!n->utcp && n != mesh->self) {
2598 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2602 pthread_mutex_unlock(&mesh->mesh_mutex);
2605 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) {
2607 abort(); // TODO: handle non-NULL data
2610 if(!mesh || !node) {
2611 meshlink_errno = MESHLINK_EINVAL;
2615 node_t *n = (node_t *)node;
2618 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2619 mesh->receive_cb = channel_receive;
2622 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2627 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2629 channel->receive_cb = cb;
2630 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2633 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2641 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) {
2642 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2645 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2646 if(!mesh || !channel) {
2647 meshlink_errno = MESHLINK_EINVAL;
2651 utcp_shutdown(channel->c, direction);
2654 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2655 if(!mesh || !channel) {
2656 meshlink_errno = MESHLINK_EINVAL;
2660 utcp_close(channel->c);
2664 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2665 if(!mesh || !channel) {
2666 meshlink_errno = MESHLINK_EINVAL;
2675 meshlink_errno = MESHLINK_EINVAL;
2679 // TODO: more finegrained locking.
2680 // Ideally we want to put the data into the UTCP connection's send buffer.
2681 // Then, preferrably only if there is room in the receiver window,
2682 // kick the meshlink thread to go send packets.
2684 pthread_mutex_lock(&mesh->mesh_mutex);
2685 ssize_t retval = utcp_send(channel->c, data, len);
2686 pthread_mutex_unlock(&mesh->mesh_mutex);
2689 meshlink_errno = MESHLINK_ENETWORK;
2695 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2696 if(!mesh || !channel) {
2697 meshlink_errno = MESHLINK_EINVAL;
2701 return channel->c->flags;
2704 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2705 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2706 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2709 if(mesh->node_status_cb) {
2710 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2714 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2715 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2719 n->status.duplicate = true;
2720 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2723 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2727 meshlink_errno = MESHLINK_EINVAL;
2731 pthread_mutex_lock(&mesh->mesh_mutex);
2733 if(mesh->discovery == enable) {
2737 if(mesh->threadstarted) {
2739 discovery_start(mesh);
2741 discovery_stop(mesh);
2745 mesh->discovery = enable;
2748 pthread_mutex_unlock(&mesh->mesh_mutex);
2752 meshlink_errno = MESHLINK_ENOTSUP;
2756 static void __attribute__((constructor)) meshlink_init(void) {
2759 randomize(&seed, sizeof(seed));
2763 static void __attribute__((destructor)) meshlink_exit(void) {
2767 /// Device class traits
2768 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2769 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2770 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2771 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2772 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN