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);
359 // This gets the hostname part for use in invitation URLs
360 static char *get_my_hostname(meshlink_handle_t *mesh) {
361 char *hostname[3] = {NULL};
362 char *port[3] = {NULL};
363 char *hostport = NULL;
365 // Use the best Address statement in our own host config file
366 char filename[PATH_MAX] = "";
367 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
368 scan_for_hostname(filename, &hostname[0], &port[0]);
370 hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET);
371 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET6);
373 // Concatenate all unique address to the hostport string
374 for(int i = 0; i < 3; i++) {
379 // Ignore duplicate hostnames
382 for(int j = 0; i < j; j++) {
383 if(safe_streq(hostname[i], hostname[j]) && safe_streq(port[i], port[j])) {
397 // Ensure we have the same addresses in our own host config file.
399 xasprintf(&tmphostport, "%s %s", hostname[i], port[i] ? port[i] : mesh->myport);
400 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
403 // Append the address to the hostport string
405 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i] ? port[i] : mesh->myport);
409 hostport = newhostport;
415 static char *get_line(const char **data) {
416 if(!data || !*data) {
425 static char line[1024];
426 const char *end = strchr(*data, '\n');
427 size_t len = end ? (size_t)(end - *data) : strlen(*data);
429 if(len >= sizeof(line)) {
430 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
434 if(len && !isprint(**data)) {
438 memcpy(line, *data, len);
450 static char *get_value(const char *data, const char *var) {
451 char *line = get_line(&data);
457 char *sep = line + strcspn(line, " \t=");
458 char *val = sep + strspn(sep, " \t");
461 val += 1 + strspn(val + 1, " \t");
466 if(strcasecmp(line, var)) {
473 static bool try_bind(int port) {
474 struct addrinfo *ai = NULL;
475 struct addrinfo hint = {
476 .ai_flags = AI_PASSIVE,
477 .ai_family = AF_UNSPEC,
478 .ai_socktype = SOCK_STREAM,
479 .ai_protocol = IPPROTO_TCP,
483 snprintf(portstr, sizeof(portstr), "%d", port);
485 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
490 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
497 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
512 int check_port(meshlink_handle_t *mesh) {
513 for(int i = 0; i < 1000; i++) {
514 int port = 0x1000 + (rand() & 0x7fff);
517 char filename[PATH_MAX];
518 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
519 FILE *f = fopen(filename, "a");
522 meshlink_errno = MESHLINK_ESTORAGE;
523 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
527 fprintf(f, "Port = %d\n", port);
533 meshlink_errno = MESHLINK_ENETWORK;
534 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
538 static void deltree(const char *dirname) {
539 DIR *d = opendir(dirname);
544 while((ent = readdir(d))) {
545 if(ent->d_name[0] == '.') {
549 char filename[PATH_MAX];
550 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
552 if(unlink(filename)) {
563 static bool finalize_join(meshlink_handle_t *mesh) {
564 char *name = xstrdup(get_value(mesh->data, "Name"));
567 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
571 if(!check_id(name)) {
572 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
576 char filename[PATH_MAX];
577 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
579 FILE *f = fopen(filename, "w");
582 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
586 fprintf(f, "Name = %s\n", name);
588 // Wipe all old host config files and invitations
589 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
592 if(mkdir(filename, 0777) && errno != EEXIST) {
593 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
597 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
600 // Create a new host config file for ourself
601 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
602 FILE *fh = fopen(filename, "w");
605 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
610 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
611 // Other chunks go unfiltered to their respective host config files
612 const char *p = mesh->data;
615 while((l = get_line(&p))) {
621 // Split line into variable and value
622 int len = strcspn(l, "\t =");
624 value += strspn(value, "\t ");
628 value += strspn(value, "\t ");
634 if(!strcasecmp(l, "Name"))
635 if(strcmp(value, name)) {
639 } else if(!strcasecmp(l, "NetName")) {
643 // Check the list of known variables
647 for(i = 0; variables[i].name; i++) {
648 if(strcasecmp(l, variables[i].name)) {
656 // Ignore unknown and unsafe variables
658 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
660 } else if(!(variables[i].type & VAR_SAFE)) {
661 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
665 // Copy the safe variable to the right config file
666 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
671 while(l && !strcasecmp(l, "Name")) {
672 if(!check_id(value)) {
673 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
677 if(!strcmp(value, name)) {
678 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
682 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
683 f = fopen(filename, "w");
686 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
690 while((l = get_line(&p))) {
691 if(!strcmp(l, "#---------------------------------------------------------------#")) {
695 int len = strcspn(l, "\t =");
697 if(len == 4 && !strncasecmp(l, "Name", 4)) {
699 value += strspn(value, "\t ");
703 value += strspn(value, "\t ");
717 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
724 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
725 fprintf(fh, "Port = %s\n", mesh->myport);
729 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
733 free(mesh->self->name);
734 free(mesh->self->connection->name);
735 mesh->name = xstrdup(name);
736 mesh->self->name = xstrdup(name);
737 mesh->self->connection->name = name;
739 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
741 load_all_nodes(mesh);
746 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
748 meshlink_handle_t *mesh = handle;
749 const char *ptr = data;
752 int result = send(mesh->sock, ptr, len, 0);
754 if(result == -1 && errno == EINTR) {
756 } else if(result <= 0) {
767 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
768 meshlink_handle_t *mesh = handle;
771 case SPTPS_HANDSHAKE:
772 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
775 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
776 memcpy(mesh->data + mesh->thedatalen, msg, len);
777 mesh->thedatalen += len;
778 mesh->data[mesh->thedatalen] = 0;
782 mesh->thedatalen = 0;
783 return finalize_join(mesh);
786 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
787 shutdown(mesh->sock, SHUT_RDWR);
788 mesh->success = true;
798 static bool recvline(meshlink_handle_t *mesh, size_t len) {
799 char *newline = NULL;
805 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
806 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
808 if(result == -1 && errno == EINTR) {
810 } else if(result <= 0) {
814 mesh->blen += result;
817 if((size_t)(newline - mesh->buffer) >= len) {
821 len = newline - mesh->buffer;
823 memcpy(mesh->line, mesh->buffer, len);
825 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
826 mesh->blen -= len + 1;
830 static bool sendline(int fd, char *format, ...) {
831 static char buffer[4096];
836 va_start(ap, format);
837 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
840 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
848 int result = send(fd, p, blen, MSG_NOSIGNAL);
850 if(result == -1 && errno == EINTR) {
852 } else if(result <= 0) {
863 static const char *errstr[] = {
864 [MESHLINK_OK] = "No error",
865 [MESHLINK_EINVAL] = "Invalid argument",
866 [MESHLINK_ENOMEM] = "Out of memory",
867 [MESHLINK_ENOENT] = "No such node",
868 [MESHLINK_EEXIST] = "Node already exists",
869 [MESHLINK_EINTERNAL] = "Internal error",
870 [MESHLINK_ERESOLV] = "Could not resolve hostname",
871 [MESHLINK_ESTORAGE] = "Storage error",
872 [MESHLINK_ENETWORK] = "Network error",
873 [MESHLINK_EPEER] = "Error communicating with peer",
874 [MESHLINK_ENOTSUP] = "Operation not supported",
875 [MESHLINK_EBUSY] = "MeshLink instance already in use",
878 const char *meshlink_strerror(meshlink_errno_t err) {
879 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
880 return "Invalid error code";
886 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
889 char pubname[PATH_MAX], privname[PATH_MAX];
891 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
893 if(!(key = ecdsa_generate())) {
894 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
895 meshlink_errno = MESHLINK_EINTERNAL;
898 logger(mesh, MESHLINK_DEBUG, "Done.\n");
901 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
902 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
903 meshlink_errno = MESHLINK_ESTORAGE;
907 f = fopen(privname, "wb");
910 meshlink_errno = MESHLINK_ESTORAGE;
915 fchmod(fileno(f), 0600);
918 if(!ecdsa_write_pem_private_key(key, f)) {
919 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
922 meshlink_errno = MESHLINK_EINTERNAL;
928 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
929 f = fopen(pubname, "a");
932 meshlink_errno = MESHLINK_ESTORAGE;
936 char *pubkey = ecdsa_get_base64_public_key(key);
937 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
946 static struct timeval idle(event_loop_t *loop, void *data) {
948 meshlink_handle_t *mesh = data;
949 struct timeval t, tmin = {3600, 0};
951 for splay_each(node_t, n, mesh->nodes) {
956 t = utcp_timeout(n->utcp);
958 if(timercmp(&t, &tmin, <)) {
966 // Get our local address(es) by simulating connecting to an Internet host.
967 static void add_local_addresses(meshlink_handle_t *mesh) {
968 char host[NI_MAXHOST];
969 char entry[MAX_STRING_SIZE];
973 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
974 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
975 append_config_file(mesh, mesh->name, "Address", entry);
980 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
981 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
982 append_config_file(mesh, mesh->name, "Address", entry);
986 static bool meshlink_setup(meshlink_handle_t *mesh) {
987 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
988 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
989 meshlink_errno = MESHLINK_ESTORAGE;
993 char filename[PATH_MAX];
994 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
996 if(mkdir(filename, 0777) && errno != EEXIST) {
997 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
998 meshlink_errno = MESHLINK_ESTORAGE;
1002 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1004 if(!access(filename, F_OK)) {
1005 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1006 meshlink_errno = MESHLINK_EEXIST;
1010 FILE *f = fopen(filename, "w");
1013 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1014 meshlink_errno = MESHLINK_ESTORAGE;
1018 fprintf(f, "Name = %s\n", mesh->name);
1021 if(!ecdsa_keygen(mesh)) {
1022 meshlink_errno = MESHLINK_EINTERNAL;
1027 if(check_port(mesh) == 0) {
1028 meshlink_errno = MESHLINK_ENETWORK;
1036 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1037 // Validate arguments provided by the application
1038 bool usingname = false;
1040 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1042 if(!confbase || !*confbase) {
1043 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1044 meshlink_errno = MESHLINK_EINVAL;
1048 if(!appname || !*appname) {
1049 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1050 meshlink_errno = MESHLINK_EINVAL;
1054 if(strchr(appname, ' ')) {
1055 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1056 meshlink_errno = MESHLINK_EINVAL;
1060 if(!name || !*name) {
1061 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1063 } else { //check name only if there is a name != NULL
1065 if(!check_id(name)) {
1066 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1067 meshlink_errno = MESHLINK_EINVAL;
1074 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1075 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1076 meshlink_errno = MESHLINK_EINVAL;
1080 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1081 mesh->confbase = xstrdup(confbase);
1082 mesh->appname = xstrdup(appname);
1083 mesh->devclass = devclass;
1084 mesh->discovery = true;
1085 mesh->invitation_timeout = 604800; // 1 week
1088 mesh->name = xstrdup(name);
1092 pthread_mutexattr_t attr;
1093 pthread_mutexattr_init(&attr);
1094 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1095 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1097 mesh->threadstarted = false;
1098 event_loop_init(&mesh->loop);
1099 mesh->loop.data = mesh;
1101 meshlink_queue_init(&mesh->outpacketqueue);
1103 // Check whether meshlink.conf already exists
1105 char filename[PATH_MAX];
1106 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1108 if(access(filename, R_OK)) {
1109 if(errno == ENOENT) {
1110 // If not, create it
1111 if(!meshlink_setup(mesh)) {
1112 // meshlink_errno is set by meshlink_setup()
1116 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1117 meshlink_close(mesh);
1118 meshlink_errno = MESHLINK_ESTORAGE;
1123 // Open the configuration file and lock it
1125 mesh->conffile = fopen(filename, "r");
1127 if(!mesh->conffile) {
1128 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1129 meshlink_close(mesh);
1130 meshlink_errno = MESHLINK_ESTORAGE;
1135 fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1139 // TODO: use _locking()?
1142 if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1143 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1144 meshlink_close(mesh);
1145 meshlink_errno = MESHLINK_EBUSY;
1151 // Read the configuration
1153 init_configuration(&mesh->config);
1155 if(!read_server_config(mesh)) {
1156 meshlink_close(mesh);
1157 meshlink_errno = MESHLINK_ESTORAGE;
1162 struct WSAData wsa_state;
1164 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1168 // Setup up everything
1169 // TODO: we should not open listening sockets yet
1171 if(!setup_network(mesh)) {
1172 meshlink_close(mesh);
1173 meshlink_errno = MESHLINK_ENETWORK;
1177 add_local_addresses(mesh);
1179 idle_set(&mesh->loop, idle, mesh);
1181 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1185 static void *meshlink_main_loop(void *arg) {
1186 meshlink_handle_t *mesh = arg;
1188 pthread_mutex_lock(&(mesh->mesh_mutex));
1190 try_outgoing_connections(mesh);
1192 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1194 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1196 pthread_mutex_unlock(&(mesh->mesh_mutex));
1200 bool meshlink_start(meshlink_handle_t *mesh) {
1202 meshlink_errno = MESHLINK_EINVAL;
1206 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1208 pthread_mutex_lock(&(mesh->mesh_mutex));
1210 if(mesh->threadstarted) {
1211 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1212 pthread_mutex_unlock(&(mesh->mesh_mutex));
1216 if(mesh->listen_socket[0].tcp.fd < 0) {
1217 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1218 meshlink_errno = MESHLINK_ENETWORK;
1222 mesh->thedatalen = 0;
1224 // TODO: open listening sockets first
1226 //Check that a valid name is set
1228 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1229 meshlink_errno = MESHLINK_EINVAL;
1230 pthread_mutex_unlock(&(mesh->mesh_mutex));
1234 // Start the main thread
1236 event_loop_start(&mesh->loop);
1238 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1239 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1240 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1241 meshlink_errno = MESHLINK_EINTERNAL;
1242 event_loop_stop(&mesh->loop);
1243 pthread_mutex_unlock(&(mesh->mesh_mutex));
1247 mesh->threadstarted = true;
1251 if(mesh->discovery) {
1252 discovery_start(mesh);
1257 pthread_mutex_unlock(&(mesh->mesh_mutex));
1261 void meshlink_stop(meshlink_handle_t *mesh) {
1263 meshlink_errno = MESHLINK_EINVAL;
1267 pthread_mutex_lock(&(mesh->mesh_mutex));
1268 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1273 if(mesh->discovery) {
1274 discovery_stop(mesh);
1279 // Shut down the main thread
1280 event_loop_stop(&mesh->loop);
1282 // Send ourselves a UDP packet to kick the event loop
1283 for(int i = 0; i < mesh->listen_sockets; i++) {
1285 socklen_t salen = sizeof(sa.sa);
1287 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1288 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1292 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1293 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1297 if(mesh->threadstarted) {
1298 // Wait for the main thread to finish
1299 pthread_mutex_unlock(&(mesh->mesh_mutex));
1300 pthread_join(mesh->thread, NULL);
1301 pthread_mutex_lock(&(mesh->mesh_mutex));
1303 mesh->threadstarted = false;
1306 // Close all metaconnections
1307 if(mesh->connections) {
1308 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1310 connection_t *c = node->data;
1312 terminate_connection(mesh, c, false);
1316 if(mesh->outgoings) {
1317 list_delete_list(mesh->outgoings);
1318 mesh->outgoings = NULL;
1321 pthread_mutex_unlock(&(mesh->mesh_mutex));
1324 void meshlink_close(meshlink_handle_t *mesh) {
1325 if(!mesh || !mesh->confbase) {
1326 meshlink_errno = MESHLINK_EINVAL;
1330 // stop can be called even if mesh has not been started
1331 meshlink_stop(mesh);
1333 // lock is not released after this
1334 pthread_mutex_lock(&(mesh->mesh_mutex));
1336 // Close and free all resources used.
1338 close_network_connections(mesh);
1340 logger(mesh, MESHLINK_INFO, "Terminating");
1342 exit_configuration(&mesh->config);
1343 event_loop_exit(&mesh->loop);
1347 if(mesh->confbase) {
1353 ecdsa_free(mesh->invitation_key);
1356 free(mesh->appname);
1357 free(mesh->confbase);
1358 pthread_mutex_destroy(&(mesh->mesh_mutex));
1360 if(mesh->conffile) {
1361 fclose(mesh->conffile);
1364 memset(mesh, 0, sizeof(*mesh));
1369 bool meshlink_destroy(const char *confbase) {
1371 meshlink_errno = MESHLINK_EINVAL;
1375 char filename[PATH_MAX];
1376 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1378 if(unlink(filename)) {
1379 if(errno == ENOENT) {
1380 meshlink_errno = MESHLINK_ENOENT;
1383 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1384 meshlink_errno = MESHLINK_ESTORAGE;
1394 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1396 meshlink_errno = MESHLINK_EINVAL;
1400 pthread_mutex_lock(&(mesh->mesh_mutex));
1401 mesh->receive_cb = cb;
1402 pthread_mutex_unlock(&(mesh->mesh_mutex));
1405 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1407 meshlink_errno = MESHLINK_EINVAL;
1411 pthread_mutex_lock(&(mesh->mesh_mutex));
1412 mesh->node_status_cb = cb;
1413 pthread_mutex_unlock(&(mesh->mesh_mutex));
1416 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1418 meshlink_errno = MESHLINK_EINVAL;
1422 pthread_mutex_lock(&(mesh->mesh_mutex));
1423 mesh->node_duplicate_cb = cb;
1424 pthread_mutex_unlock(&(mesh->mesh_mutex));
1427 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1429 pthread_mutex_lock(&(mesh->mesh_mutex));
1431 mesh->log_level = cb ? level : 0;
1432 pthread_mutex_unlock(&(mesh->mesh_mutex));
1435 global_log_level = cb ? level : 0;
1439 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1440 meshlink_packethdr_t *hdr;
1442 // Validate arguments
1443 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1444 meshlink_errno = MESHLINK_EINVAL;
1453 meshlink_errno = MESHLINK_EINVAL;
1457 // Prepare the packet
1458 vpn_packet_t *packet = malloc(sizeof(*packet));
1461 meshlink_errno = MESHLINK_ENOMEM;
1465 packet->probe = false;
1466 packet->tcp = false;
1467 packet->len = len + sizeof(*hdr);
1469 hdr = (meshlink_packethdr_t *)packet->data;
1470 memset(hdr, 0, sizeof(*hdr));
1471 // leave the last byte as 0 to make sure strings are always
1472 // null-terminated if they are longer than the buffer
1473 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1474 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1476 memcpy(packet->data + sizeof(*hdr), data, len);
1479 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1481 meshlink_errno = MESHLINK_ENOMEM;
1485 // Notify event loop
1486 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1491 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1493 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1499 mesh->self->in_packets++;
1500 mesh->self->in_bytes += packet->len;
1501 route(mesh, mesh->self, packet);
1504 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1505 if(!mesh || !destination) {
1506 meshlink_errno = MESHLINK_EINVAL;
1510 pthread_mutex_lock(&(mesh->mesh_mutex));
1512 node_t *n = (node_t *)destination;
1514 if(!n->status.reachable) {
1515 pthread_mutex_unlock(&(mesh->mesh_mutex));
1518 } else if(n->mtuprobes > 30 && n->minmtu) {
1519 pthread_mutex_unlock(&(mesh->mesh_mutex));
1522 pthread_mutex_unlock(&(mesh->mesh_mutex));
1527 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1528 if(!mesh || !node) {
1529 meshlink_errno = MESHLINK_EINVAL;
1533 pthread_mutex_lock(&(mesh->mesh_mutex));
1535 node_t *n = (node_t *)node;
1537 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1538 meshlink_errno = MESHLINK_EINTERNAL;
1539 pthread_mutex_unlock(&(mesh->mesh_mutex));
1543 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1546 meshlink_errno = MESHLINK_EINTERNAL;
1549 pthread_mutex_unlock(&(mesh->mesh_mutex));
1553 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1555 meshlink_errno = MESHLINK_EINVAL;
1559 return (meshlink_node_t *)mesh->self;
1562 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1563 if(!mesh || !name) {
1564 meshlink_errno = MESHLINK_EINVAL;
1568 meshlink_node_t *node = NULL;
1570 pthread_mutex_lock(&(mesh->mesh_mutex));
1571 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1572 pthread_mutex_unlock(&(mesh->mesh_mutex));
1576 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1577 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1578 meshlink_errno = MESHLINK_EINVAL;
1582 meshlink_node_t **result;
1585 pthread_mutex_lock(&(mesh->mesh_mutex));
1587 *nmemb = mesh->nodes->count;
1588 result = realloc(nodes, *nmemb * sizeof(*nodes));
1591 meshlink_node_t **p = result;
1593 for splay_each(node_t, n, mesh->nodes) {
1594 *p++ = (meshlink_node_t *)n;
1599 meshlink_errno = MESHLINK_ENOMEM;
1602 pthread_mutex_unlock(&(mesh->mesh_mutex));
1607 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1608 if(!mesh || !data || !len || !signature || !siglen) {
1609 meshlink_errno = MESHLINK_EINVAL;
1613 if(*siglen < MESHLINK_SIGLEN) {
1614 meshlink_errno = MESHLINK_EINVAL;
1618 pthread_mutex_lock(&(mesh->mesh_mutex));
1620 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1621 meshlink_errno = MESHLINK_EINTERNAL;
1622 pthread_mutex_unlock(&(mesh->mesh_mutex));
1626 *siglen = MESHLINK_SIGLEN;
1627 pthread_mutex_unlock(&(mesh->mesh_mutex));
1631 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1632 if(!mesh || !data || !len || !signature) {
1633 meshlink_errno = MESHLINK_EINVAL;
1637 if(siglen != MESHLINK_SIGLEN) {
1638 meshlink_errno = MESHLINK_EINVAL;
1642 pthread_mutex_lock(&(mesh->mesh_mutex));
1646 struct node_t *n = (struct node_t *)source;
1647 node_read_ecdsa_public_key(mesh, n);
1650 meshlink_errno = MESHLINK_EINTERNAL;
1653 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1656 pthread_mutex_unlock(&(mesh->mesh_mutex));
1660 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1661 char filename[PATH_MAX];
1663 pthread_mutex_lock(&(mesh->mesh_mutex));
1665 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1667 if(mkdir(filename, 0700) && errno != EEXIST) {
1668 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1669 meshlink_errno = MESHLINK_ESTORAGE;
1670 pthread_mutex_unlock(&(mesh->mesh_mutex));
1674 // Count the number of valid invitations, clean up old ones
1675 DIR *dir = opendir(filename);
1678 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1679 meshlink_errno = MESHLINK_ESTORAGE;
1680 pthread_mutex_unlock(&(mesh->mesh_mutex));
1687 time_t deadline = time(NULL) - 604800; // 1 week in the past
1689 while((ent = readdir(dir))) {
1690 if(strlen(ent->d_name) != 24) {
1694 char invname[PATH_MAX];
1697 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1698 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1702 if(!stat(invname, &st)) {
1703 if(mesh->invitation_key && deadline < st.st_mtime) {
1709 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1715 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1717 meshlink_errno = MESHLINK_ESTORAGE;
1718 pthread_mutex_unlock(&(mesh->mesh_mutex));
1724 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1726 // Remove the key if there are no outstanding invitations.
1730 if(mesh->invitation_key) {
1731 ecdsa_free(mesh->invitation_key);
1732 mesh->invitation_key = NULL;
1736 if(mesh->invitation_key) {
1737 pthread_mutex_unlock(&(mesh->mesh_mutex));
1741 // Create a new key if necessary.
1742 FILE *f = fopen(filename, "rb");
1745 if(errno != ENOENT) {
1746 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1747 meshlink_errno = MESHLINK_ESTORAGE;
1748 pthread_mutex_unlock(&(mesh->mesh_mutex));
1752 mesh->invitation_key = ecdsa_generate();
1754 if(!mesh->invitation_key) {
1755 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1756 meshlink_errno = MESHLINK_EINTERNAL;
1757 pthread_mutex_unlock(&(mesh->mesh_mutex));
1761 f = fopen(filename, "wb");
1764 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1765 meshlink_errno = MESHLINK_ESTORAGE;
1766 pthread_mutex_unlock(&(mesh->mesh_mutex));
1770 chmod(filename, 0600);
1771 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1774 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1777 if(!mesh->invitation_key) {
1778 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1779 meshlink_errno = MESHLINK_ESTORAGE;
1783 pthread_mutex_unlock(&(mesh->mesh_mutex));
1784 return mesh->invitation_key;
1787 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1788 if(!mesh || !node || !address) {
1789 meshlink_errno = MESHLINK_EINVAL;
1793 if(!is_valid_hostname(address)) {
1794 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1795 meshlink_errno = MESHLINK_EINVAL;
1799 if(port && !is_valid_port(port)) {
1800 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1801 meshlink_errno = MESHLINK_EINVAL;
1805 char *canonical_address;
1808 xasprintf(&canonical_address, "%s %s", address, port);
1810 canonical_address = xstrdup(address);
1813 pthread_mutex_lock(&(mesh->mesh_mutex));
1814 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1815 pthread_mutex_unlock(&(mesh->mesh_mutex));
1817 free(canonical_address);
1821 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1822 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1825 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1827 meshlink_errno = MESHLINK_EINVAL;
1831 char *address = meshlink_get_external_address(mesh);
1839 pthread_mutex_lock(&(mesh->mesh_mutex));
1840 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1841 pthread_mutex_unlock(&(mesh->mesh_mutex));
1847 int meshlink_get_port(meshlink_handle_t *mesh) {
1849 meshlink_errno = MESHLINK_EINVAL;
1854 meshlink_errno = MESHLINK_EINTERNAL;
1858 return atoi(mesh->myport);
1861 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1862 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1863 meshlink_errno = MESHLINK_EINVAL;
1867 if(mesh->myport && port == atoi(mesh->myport)) {
1871 if(!try_bind(port)) {
1872 meshlink_errno = MESHLINK_ENETWORK;
1878 pthread_mutex_lock(&(mesh->mesh_mutex));
1880 if(mesh->threadstarted) {
1881 meshlink_errno = MESHLINK_EINVAL;
1885 close_network_connections(mesh);
1886 exit_configuration(&mesh->config);
1889 snprintf(portstr, sizeof(portstr), "%d", port);
1890 portstr[sizeof(portstr) - 1] = 0;
1892 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1894 init_configuration(&mesh->config);
1896 if(!read_server_config(mesh)) {
1897 meshlink_errno = MESHLINK_ESTORAGE;
1898 } else if(!setup_network(mesh)) {
1899 meshlink_errno = MESHLINK_ENETWORK;
1905 pthread_mutex_unlock(&(mesh->mesh_mutex));
1910 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1911 mesh->invitation_timeout = timeout;
1914 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1916 meshlink_errno = MESHLINK_EINVAL;
1920 pthread_mutex_lock(&(mesh->mesh_mutex));
1922 // Check validity of the new node's name
1923 if(!check_id(name)) {
1924 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1925 meshlink_errno = MESHLINK_EINVAL;
1926 pthread_mutex_unlock(&(mesh->mesh_mutex));
1930 // Ensure no host configuration file with that name exists
1931 char filename[PATH_MAX];
1932 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1934 if(!access(filename, F_OK)) {
1935 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1936 meshlink_errno = MESHLINK_EEXIST;
1937 pthread_mutex_unlock(&(mesh->mesh_mutex));
1941 // Ensure no other nodes know about this name
1942 if(meshlink_get_node(mesh, name)) {
1943 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1944 meshlink_errno = MESHLINK_EEXIST;
1945 pthread_mutex_unlock(&(mesh->mesh_mutex));
1949 // Get the local address
1950 char *address = get_my_hostname(mesh);
1953 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1954 meshlink_errno = MESHLINK_ERESOLV;
1955 pthread_mutex_unlock(&(mesh->mesh_mutex));
1959 if(!refresh_invitation_key(mesh)) {
1960 meshlink_errno = MESHLINK_EINTERNAL;
1961 pthread_mutex_unlock(&(mesh->mesh_mutex));
1967 // Create a hash of the key.
1968 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1969 sha512(fingerprint, strlen(fingerprint), hash);
1970 b64encode_urlsafe(hash, hash, 18);
1972 // Create a random cookie for this invitation.
1974 randomize(cookie, 18);
1976 // Create a filename that doesn't reveal the cookie itself
1977 char buf[18 + strlen(fingerprint)];
1978 char cookiehash[64];
1979 memcpy(buf, cookie, 18);
1980 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1981 sha512(buf, sizeof(buf), cookiehash);
1982 b64encode_urlsafe(cookiehash, cookiehash, 18);
1984 b64encode_urlsafe(cookie, cookie, 18);
1988 // Create a file containing the details of the invitation.
1989 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1990 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1993 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1994 meshlink_errno = MESHLINK_ESTORAGE;
1995 pthread_mutex_unlock(&(mesh->mesh_mutex));
1999 FILE *f = fdopen(ifd, "w");
2005 // Fill in the details.
2006 fprintf(f, "Name = %s\n", name);
2007 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2009 // Copy Broadcast and Mode
2010 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2011 FILE *tc = fopen(filename, "r");
2016 while(fgets(buf, sizeof(buf), tc)) {
2017 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2018 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2021 // Make sure there is a newline character.
2022 if(!strchr(buf, '\n')) {
2030 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2031 meshlink_errno = MESHLINK_ESTORAGE;
2032 pthread_mutex_unlock(&(mesh->mesh_mutex));
2036 fprintf(f, "#---------------------------------------------------------------#\n");
2037 fprintf(f, "Name = %s\n", mesh->self->name);
2039 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2043 // Create an URL from the local address, key hash and cookie
2045 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2048 pthread_mutex_unlock(&(mesh->mesh_mutex));
2052 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2053 if(!mesh || !invitation) {
2054 meshlink_errno = MESHLINK_EINVAL;
2058 pthread_mutex_lock(&(mesh->mesh_mutex));
2060 //Before doing meshlink_join make sure we are not connected to another mesh
2061 if(mesh->threadstarted) {
2062 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2063 meshlink_errno = MESHLINK_EINVAL;
2064 pthread_mutex_unlock(&(mesh->mesh_mutex));
2068 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2069 char copy[strlen(invitation) + 1];
2070 strcpy(copy, invitation);
2072 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2074 char *slash = strchr(copy, '/');
2082 if(strlen(slash) != 48) {
2086 char *address = copy;
2089 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2093 // Generate a throw-away key for the invitation.
2094 ecdsa_t *key = ecdsa_generate();
2097 meshlink_errno = MESHLINK_EINTERNAL;
2098 pthread_mutex_unlock(&(mesh->mesh_mutex));
2102 char *b64key = ecdsa_get_base64_public_key(key);
2106 while(address && *address) {
2107 // We allow commas in the address part to support multiple addresses in one invitation URL.
2108 comma = strchr(address, ',');
2114 // Split of the port
2115 port = strrchr(address, ':');
2123 // IPv6 address are enclosed in brackets, per RFC 3986
2124 if(*address == '[') {
2126 char *bracket = strchr(address, ']');
2139 // Connect to the meshlink daemon mentioned in the URL.
2140 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2143 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2144 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2146 if(mesh->sock == -1) {
2147 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2148 meshlink_errno = MESHLINK_ENETWORK;
2152 set_timeout(mesh->sock, 5000);
2154 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2155 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2156 meshlink_errno = MESHLINK_ENETWORK;
2157 closesocket(mesh->sock);
2165 meshlink_errno = MESHLINK_ERESOLV;
2168 if(mesh->sock != -1 || !comma) {
2175 if(mesh->sock == -1) {
2176 pthread_mutex_unlock(&mesh->mesh_mutex);
2180 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2182 // Tell him we have an invitation, and give him our throw-away key.
2186 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2187 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2188 closesocket(mesh->sock);
2189 meshlink_errno = MESHLINK_ENETWORK;
2190 pthread_mutex_unlock(&(mesh->mesh_mutex));
2196 char hisname[4096] = "";
2197 int code, hismajor, hisminor = 0;
2199 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) {
2200 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2201 closesocket(mesh->sock);
2202 meshlink_errno = MESHLINK_ENETWORK;
2203 pthread_mutex_unlock(&(mesh->mesh_mutex));
2207 // Check if the hash of the key he gave us matches the hash in the URL.
2208 char *fingerprint = mesh->line + 2;
2211 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2212 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2213 meshlink_errno = MESHLINK_EINTERNAL;
2214 pthread_mutex_unlock(&(mesh->mesh_mutex));
2218 if(memcmp(hishash, mesh->hash, 18)) {
2219 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2220 meshlink_errno = MESHLINK_EPEER;
2221 pthread_mutex_unlock(&(mesh->mesh_mutex));
2226 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2229 meshlink_errno = MESHLINK_EINTERNAL;
2230 pthread_mutex_unlock(&(mesh->mesh_mutex));
2234 // Start an SPTPS session
2235 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2236 meshlink_errno = MESHLINK_EINTERNAL;
2237 pthread_mutex_unlock(&(mesh->mesh_mutex));
2241 // Feed rest of input buffer to SPTPS
2242 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2243 meshlink_errno = MESHLINK_EPEER;
2244 pthread_mutex_unlock(&(mesh->mesh_mutex));
2250 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2252 if(errno == EINTR) {
2256 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2257 meshlink_errno = MESHLINK_ENETWORK;
2258 pthread_mutex_unlock(&(mesh->mesh_mutex));
2262 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2263 meshlink_errno = MESHLINK_EPEER;
2264 pthread_mutex_unlock(&(mesh->mesh_mutex));
2269 sptps_stop(&mesh->sptps);
2272 closesocket(mesh->sock);
2274 if(!mesh->success) {
2275 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2276 meshlink_errno = MESHLINK_EPEER;
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2281 pthread_mutex_unlock(&(mesh->mesh_mutex));
2285 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2286 meshlink_errno = MESHLINK_EINVAL;
2287 pthread_mutex_unlock(&(mesh->mesh_mutex));
2291 char *meshlink_export(meshlink_handle_t *mesh) {
2293 meshlink_errno = MESHLINK_EINVAL;
2297 pthread_mutex_lock(&(mesh->mesh_mutex));
2299 char filename[PATH_MAX];
2300 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2301 FILE *f = fopen(filename, "r");
2304 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2305 meshlink_errno = MESHLINK_ESTORAGE;
2306 pthread_mutex_unlock(&(mesh->mesh_mutex));
2310 fseek(f, 0, SEEK_END);
2311 int fsize = ftell(f);
2314 size_t len = fsize + 9 + strlen(mesh->self->name);
2315 char *buf = xmalloc(len);
2316 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2318 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2319 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2322 meshlink_errno = MESHLINK_ESTORAGE;
2323 pthread_mutex_unlock(&(mesh->mesh_mutex));
2330 pthread_mutex_unlock(&(mesh->mesh_mutex));
2334 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2335 if(!mesh || !data) {
2336 meshlink_errno = MESHLINK_EINVAL;
2340 pthread_mutex_lock(&(mesh->mesh_mutex));
2342 if(strncmp(data, "Name = ", 7)) {
2343 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2344 meshlink_errno = MESHLINK_EPEER;
2345 pthread_mutex_unlock(&(mesh->mesh_mutex));
2349 char *end = strchr(data + 7, '\n');
2352 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2353 meshlink_errno = MESHLINK_EPEER;
2354 pthread_mutex_unlock(&(mesh->mesh_mutex));
2358 int len = end - (data + 7);
2360 memcpy(name, data + 7, len);
2363 if(!check_id(name)) {
2364 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2365 meshlink_errno = MESHLINK_EPEER;
2366 pthread_mutex_unlock(&(mesh->mesh_mutex));
2370 char filename[PATH_MAX];
2371 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2373 if(!access(filename, F_OK)) {
2374 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2375 meshlink_errno = MESHLINK_EEXIST;
2376 pthread_mutex_unlock(&(mesh->mesh_mutex));
2380 if(errno != ENOENT) {
2381 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2382 meshlink_errno = MESHLINK_ESTORAGE;
2383 pthread_mutex_unlock(&(mesh->mesh_mutex));
2387 FILE *f = fopen(filename, "w");
2390 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2391 meshlink_errno = MESHLINK_ESTORAGE;
2392 pthread_mutex_unlock(&(mesh->mesh_mutex));
2396 fwrite(end + 1, strlen(end + 1), 1, f);
2399 load_all_nodes(mesh);
2401 pthread_mutex_unlock(&(mesh->mesh_mutex));
2405 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2406 if(!mesh || !node) {
2407 meshlink_errno = MESHLINK_EINVAL;
2411 pthread_mutex_lock(&(mesh->mesh_mutex));
2415 n->status.blacklisted = true;
2416 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2418 //Make blacklisting persistent in the config file
2419 append_config_file(mesh, n->name, "blacklisted", "yes");
2421 //Immediately terminate any connections we have with the blacklisted node
2422 for list_each(connection_t, c, mesh->connections) {
2424 terminate_connection(mesh, c, c->status.active);
2428 pthread_mutex_unlock(&(mesh->mesh_mutex));
2431 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2432 if(!mesh || !node) {
2433 meshlink_errno = MESHLINK_EINVAL;
2437 pthread_mutex_lock(&(mesh->mesh_mutex));
2439 node_t *n = (node_t *)node;
2440 n->status.blacklisted = false;
2442 //TODO: remove blacklisted = yes from the config file
2444 pthread_mutex_unlock(&(mesh->mesh_mutex));
2448 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2449 mesh->default_blacklist = blacklist;
2452 /* Hint that a hostname may be found at an address
2453 * See header file for detailed comment.
2455 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2456 if(!mesh || !node || !addr) {
2460 // Ignore hints about ourself.
2461 if((node_t *)node == mesh->self) {
2465 pthread_mutex_lock(&(mesh->mesh_mutex));
2467 char *host = NULL, *port = NULL, *str = NULL;
2468 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2471 xasprintf(&str, "%s %s", host, port);
2473 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2474 modify_config_file(mesh, node->name, "Address", str, 5);
2476 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2484 pthread_mutex_unlock(&(mesh->mesh_mutex));
2485 // @TODO do we want to fire off a connection attempt right away?
2488 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2490 node_t *n = utcp->priv;
2491 meshlink_handle_t *mesh = n->mesh;
2492 return mesh->channel_accept_cb;
2495 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2496 meshlink_channel_t *channel = connection->priv;
2502 node_t *n = channel->node;
2503 meshlink_handle_t *mesh = n->mesh;
2505 if(n->status.destroyed) {
2506 meshlink_channel_close(mesh, channel);
2507 } else if(channel->receive_cb) {
2508 channel->receive_cb(mesh, channel, data, len);
2514 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2515 node_t *n = utcp_connection->utcp->priv;
2521 meshlink_handle_t *mesh = n->mesh;
2523 if(!mesh->channel_accept_cb) {
2527 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2529 channel->c = utcp_connection;
2531 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2532 utcp_accept(utcp_connection, channel_recv, channel);
2538 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2539 node_t *n = utcp->priv;
2541 if(n->status.destroyed) {
2545 meshlink_handle_t *mesh = n->mesh;
2546 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2549 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2550 if(!mesh || !channel) {
2551 meshlink_errno = MESHLINK_EINVAL;
2555 channel->receive_cb = cb;
2558 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2560 node_t *n = (node_t *)source;
2566 utcp_recv(n->utcp, data, len);
2569 static void channel_poll(struct utcp_connection *connection, size_t len) {
2570 meshlink_channel_t *channel = connection->priv;
2576 node_t *n = channel->node;
2577 meshlink_handle_t *mesh = n->mesh;
2579 if(channel->poll_cb) {
2580 channel->poll_cb(mesh, channel, len);
2584 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2586 channel->poll_cb = cb;
2587 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2590 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2592 meshlink_errno = MESHLINK_EINVAL;
2596 pthread_mutex_lock(&mesh->mesh_mutex);
2597 mesh->channel_accept_cb = cb;
2598 mesh->receive_cb = channel_receive;
2600 for splay_each(node_t, n, mesh->nodes) {
2601 if(!n->utcp && n != mesh->self) {
2602 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2606 pthread_mutex_unlock(&mesh->mesh_mutex);
2609 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) {
2611 abort(); // TODO: handle non-NULL data
2614 if(!mesh || !node) {
2615 meshlink_errno = MESHLINK_EINVAL;
2619 node_t *n = (node_t *)node;
2622 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2623 mesh->receive_cb = channel_receive;
2626 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2631 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2633 channel->receive_cb = cb;
2634 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2637 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2645 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) {
2646 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2649 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2650 if(!mesh || !channel) {
2651 meshlink_errno = MESHLINK_EINVAL;
2655 utcp_shutdown(channel->c, direction);
2658 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2659 if(!mesh || !channel) {
2660 meshlink_errno = MESHLINK_EINVAL;
2664 utcp_close(channel->c);
2668 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2669 if(!mesh || !channel) {
2670 meshlink_errno = MESHLINK_EINVAL;
2679 meshlink_errno = MESHLINK_EINVAL;
2683 // TODO: more finegrained locking.
2684 // Ideally we want to put the data into the UTCP connection's send buffer.
2685 // Then, preferrably only if there is room in the receiver window,
2686 // kick the meshlink thread to go send packets.
2688 pthread_mutex_lock(&mesh->mesh_mutex);
2689 ssize_t retval = utcp_send(channel->c, data, len);
2690 pthread_mutex_unlock(&mesh->mesh_mutex);
2693 meshlink_errno = MESHLINK_ENETWORK;
2699 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2700 if(!mesh || !channel) {
2701 meshlink_errno = MESHLINK_EINVAL;
2705 return channel->c->flags;
2708 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2709 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2710 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2713 if(mesh->node_status_cb) {
2714 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2718 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2719 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2723 n->status.duplicate = true;
2724 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2727 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2731 meshlink_errno = MESHLINK_EINVAL;
2735 pthread_mutex_lock(&mesh->mesh_mutex);
2737 if(mesh->discovery == enable) {
2741 if(mesh->threadstarted) {
2743 discovery_start(mesh);
2745 discovery_stop(mesh);
2749 mesh->discovery = enable;
2752 pthread_mutex_unlock(&mesh->mesh_mutex);
2756 meshlink_errno = MESHLINK_ENOTSUP;
2760 static void __attribute__((constructor)) meshlink_init(void) {
2763 randomize(&seed, sizeof(seed));
2767 static void __attribute__((destructor)) meshlink_exit(void) {
2771 /// Device class traits
2772 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2773 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2774 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2775 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2776 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN