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",
874 const char *meshlink_strerror(meshlink_errno_t err) {
875 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
876 return "Invalid error code";
882 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
885 char pubname[PATH_MAX], privname[PATH_MAX];
887 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
889 if(!(key = ecdsa_generate())) {
890 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
891 meshlink_errno = MESHLINK_EINTERNAL;
894 logger(mesh, MESHLINK_DEBUG, "Done.\n");
897 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
898 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
899 meshlink_errno = MESHLINK_ESTORAGE;
903 f = fopen(privname, "wb");
906 meshlink_errno = MESHLINK_ESTORAGE;
911 fchmod(fileno(f), 0600);
914 if(!ecdsa_write_pem_private_key(key, f)) {
915 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
918 meshlink_errno = MESHLINK_EINTERNAL;
924 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
925 f = fopen(pubname, "a");
928 meshlink_errno = MESHLINK_ESTORAGE;
932 char *pubkey = ecdsa_get_base64_public_key(key);
933 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
942 static struct timeval idle(event_loop_t *loop, void *data) {
944 meshlink_handle_t *mesh = data;
945 struct timeval t, tmin = {3600, 0};
947 for splay_each(node_t, n, mesh->nodes) {
952 t = utcp_timeout(n->utcp);
954 if(timercmp(&t, &tmin, <)) {
962 // Get our local address(es) by simulating connecting to an Internet host.
963 static void add_local_addresses(meshlink_handle_t *mesh) {
964 char host[NI_MAXHOST];
965 char entry[MAX_STRING_SIZE];
969 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
970 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
971 append_config_file(mesh, mesh->name, "Address", entry);
976 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
977 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
978 append_config_file(mesh, mesh->name, "Address", entry);
982 static bool meshlink_setup(meshlink_handle_t *mesh) {
983 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
984 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
985 meshlink_errno = MESHLINK_ESTORAGE;
989 char filename[PATH_MAX];
990 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
992 if(mkdir(filename, 0777) && errno != EEXIST) {
993 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
994 meshlink_errno = MESHLINK_ESTORAGE;
998 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1000 if(!access(filename, F_OK)) {
1001 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1002 meshlink_errno = MESHLINK_EEXIST;
1006 FILE *f = fopen(filename, "w");
1009 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1010 meshlink_errno = MESHLINK_ESTORAGE;
1014 fprintf(f, "Name = %s\n", mesh->name);
1017 if(!ecdsa_keygen(mesh)) {
1018 meshlink_errno = MESHLINK_EINTERNAL;
1023 if(check_port(mesh) == 0) {
1024 meshlink_errno = MESHLINK_ENETWORK;
1032 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1033 // Validate arguments provided by the application
1034 bool usingname = false;
1036 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1038 if(!confbase || !*confbase) {
1039 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1040 meshlink_errno = MESHLINK_EINVAL;
1044 if(!appname || !*appname) {
1045 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1046 meshlink_errno = MESHLINK_EINVAL;
1050 if(strchr(appname, ' ')) {
1051 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1052 meshlink_errno = MESHLINK_EINVAL;
1056 if(!name || !*name) {
1057 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1059 } else { //check name only if there is a name != NULL
1061 if(!check_id(name)) {
1062 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1063 meshlink_errno = MESHLINK_EINVAL;
1070 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1071 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1072 meshlink_errno = MESHLINK_EINVAL;
1076 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1077 mesh->confbase = xstrdup(confbase);
1078 mesh->appname = xstrdup(appname);
1079 mesh->devclass = devclass;
1080 mesh->discovery = true;
1081 mesh->invitation_timeout = 604800; // 1 week
1084 mesh->name = xstrdup(name);
1088 pthread_mutexattr_t attr;
1089 pthread_mutexattr_init(&attr);
1090 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1091 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1093 mesh->threadstarted = false;
1094 event_loop_init(&mesh->loop);
1095 mesh->loop.data = mesh;
1097 meshlink_queue_init(&mesh->outpacketqueue);
1099 // Check whether meshlink.conf already exists
1101 char filename[PATH_MAX];
1102 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1104 if(access(filename, R_OK)) {
1105 if(errno == ENOENT) {
1106 // If not, create it
1107 if(!meshlink_setup(mesh)) {
1108 // meshlink_errno is set by meshlink_setup()
1112 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1113 meshlink_close(mesh);
1114 meshlink_errno = MESHLINK_ESTORAGE;
1119 // Read the configuration
1121 init_configuration(&mesh->config);
1123 if(!read_server_config(mesh)) {
1124 meshlink_close(mesh);
1125 meshlink_errno = MESHLINK_ESTORAGE;
1130 struct WSAData wsa_state;
1132 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1136 // Setup up everything
1137 // TODO: we should not open listening sockets yet
1139 if(!setup_network(mesh)) {
1140 meshlink_close(mesh);
1141 meshlink_errno = MESHLINK_ENETWORK;
1145 add_local_addresses(mesh);
1147 idle_set(&mesh->loop, idle, mesh);
1149 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1153 static void *meshlink_main_loop(void *arg) {
1154 meshlink_handle_t *mesh = arg;
1156 pthread_mutex_lock(&(mesh->mesh_mutex));
1158 try_outgoing_connections(mesh);
1160 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1162 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1164 pthread_mutex_unlock(&(mesh->mesh_mutex));
1168 bool meshlink_start(meshlink_handle_t *mesh) {
1170 meshlink_errno = MESHLINK_EINVAL;
1174 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1176 pthread_mutex_lock(&(mesh->mesh_mutex));
1178 if(mesh->threadstarted) {
1179 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1180 pthread_mutex_unlock(&(mesh->mesh_mutex));
1184 if(mesh->listen_socket[0].tcp.fd < 0) {
1185 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1186 meshlink_errno = MESHLINK_ENETWORK;
1190 mesh->thedatalen = 0;
1192 // TODO: open listening sockets first
1194 //Check that a valid name is set
1196 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1197 meshlink_errno = MESHLINK_EINVAL;
1198 pthread_mutex_unlock(&(mesh->mesh_mutex));
1202 // Start the main thread
1204 event_loop_start(&mesh->loop);
1206 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1207 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1208 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1209 meshlink_errno = MESHLINK_EINTERNAL;
1210 event_loop_stop(&mesh->loop);
1211 pthread_mutex_unlock(&(mesh->mesh_mutex));
1215 mesh->threadstarted = true;
1219 if(mesh->discovery) {
1220 discovery_start(mesh);
1225 pthread_mutex_unlock(&(mesh->mesh_mutex));
1229 void meshlink_stop(meshlink_handle_t *mesh) {
1231 meshlink_errno = MESHLINK_EINVAL;
1235 pthread_mutex_lock(&(mesh->mesh_mutex));
1236 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1241 if(mesh->discovery) {
1242 discovery_stop(mesh);
1247 // Shut down the main thread
1248 event_loop_stop(&mesh->loop);
1250 // Send ourselves a UDP packet to kick the event loop
1251 for(int i = 0; i < mesh->listen_sockets; i++) {
1253 socklen_t salen = sizeof(sa.sa);
1255 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1256 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1260 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1261 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1265 if(mesh->threadstarted) {
1266 // Wait for the main thread to finish
1267 pthread_mutex_unlock(&(mesh->mesh_mutex));
1268 pthread_join(mesh->thread, NULL);
1269 pthread_mutex_lock(&(mesh->mesh_mutex));
1271 mesh->threadstarted = false;
1274 // Close all metaconnections
1275 if(mesh->connections) {
1276 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1278 connection_t *c = node->data;
1280 terminate_connection(mesh, c, false);
1284 if(mesh->outgoings) {
1285 list_delete_list(mesh->outgoings);
1286 mesh->outgoings = NULL;
1289 pthread_mutex_unlock(&(mesh->mesh_mutex));
1292 void meshlink_close(meshlink_handle_t *mesh) {
1293 if(!mesh || !mesh->confbase) {
1294 meshlink_errno = MESHLINK_EINVAL;
1298 // stop can be called even if mesh has not been started
1299 meshlink_stop(mesh);
1301 // lock is not released after this
1302 pthread_mutex_lock(&(mesh->mesh_mutex));
1304 // Close and free all resources used.
1306 close_network_connections(mesh);
1308 logger(mesh, MESHLINK_INFO, "Terminating");
1310 exit_configuration(&mesh->config);
1311 event_loop_exit(&mesh->loop);
1315 if(mesh->confbase) {
1321 ecdsa_free(mesh->invitation_key);
1324 free(mesh->appname);
1325 free(mesh->confbase);
1326 pthread_mutex_destroy(&(mesh->mesh_mutex));
1328 memset(mesh, 0, sizeof(*mesh));
1333 bool meshlink_destroy(const char *confbase) {
1335 meshlink_errno = MESHLINK_EINVAL;
1339 char filename[PATH_MAX];
1340 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1342 if(unlink(filename)) {
1343 if(errno == ENOENT) {
1344 meshlink_errno = MESHLINK_ENOENT;
1347 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1348 meshlink_errno = MESHLINK_ESTORAGE;
1358 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1360 meshlink_errno = MESHLINK_EINVAL;
1364 pthread_mutex_lock(&(mesh->mesh_mutex));
1365 mesh->receive_cb = cb;
1366 pthread_mutex_unlock(&(mesh->mesh_mutex));
1369 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1371 meshlink_errno = MESHLINK_EINVAL;
1375 pthread_mutex_lock(&(mesh->mesh_mutex));
1376 mesh->node_status_cb = cb;
1377 pthread_mutex_unlock(&(mesh->mesh_mutex));
1380 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1382 meshlink_errno = MESHLINK_EINVAL;
1386 pthread_mutex_lock(&(mesh->mesh_mutex));
1387 mesh->node_duplicate_cb = cb;
1388 pthread_mutex_unlock(&(mesh->mesh_mutex));
1391 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1393 pthread_mutex_lock(&(mesh->mesh_mutex));
1395 mesh->log_level = cb ? level : 0;
1396 pthread_mutex_unlock(&(mesh->mesh_mutex));
1399 global_log_level = cb ? level : 0;
1403 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1404 meshlink_packethdr_t *hdr;
1406 // Validate arguments
1407 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1408 meshlink_errno = MESHLINK_EINVAL;
1417 meshlink_errno = MESHLINK_EINVAL;
1421 // Prepare the packet
1422 vpn_packet_t *packet = malloc(sizeof(*packet));
1425 meshlink_errno = MESHLINK_ENOMEM;
1429 packet->probe = false;
1430 packet->tcp = false;
1431 packet->len = len + sizeof(*hdr);
1433 hdr = (meshlink_packethdr_t *)packet->data;
1434 memset(hdr, 0, sizeof(*hdr));
1435 // leave the last byte as 0 to make sure strings are always
1436 // null-terminated if they are longer than the buffer
1437 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1438 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1440 memcpy(packet->data + sizeof(*hdr), data, len);
1443 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1445 meshlink_errno = MESHLINK_ENOMEM;
1449 // Notify event loop
1450 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1455 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1457 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1463 mesh->self->in_packets++;
1464 mesh->self->in_bytes += packet->len;
1465 route(mesh, mesh->self, packet);
1468 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1469 if(!mesh || !destination) {
1470 meshlink_errno = MESHLINK_EINVAL;
1474 pthread_mutex_lock(&(mesh->mesh_mutex));
1476 node_t *n = (node_t *)destination;
1478 if(!n->status.reachable) {
1479 pthread_mutex_unlock(&(mesh->mesh_mutex));
1482 } else if(n->mtuprobes > 30 && n->minmtu) {
1483 pthread_mutex_unlock(&(mesh->mesh_mutex));
1486 pthread_mutex_unlock(&(mesh->mesh_mutex));
1491 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1492 if(!mesh || !node) {
1493 meshlink_errno = MESHLINK_EINVAL;
1497 pthread_mutex_lock(&(mesh->mesh_mutex));
1499 node_t *n = (node_t *)node;
1501 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1502 meshlink_errno = MESHLINK_EINTERNAL;
1503 pthread_mutex_unlock(&(mesh->mesh_mutex));
1507 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1510 meshlink_errno = MESHLINK_EINTERNAL;
1513 pthread_mutex_unlock(&(mesh->mesh_mutex));
1517 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1519 meshlink_errno = MESHLINK_EINVAL;
1523 return (meshlink_node_t *)mesh->self;
1526 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1527 if(!mesh || !name) {
1528 meshlink_errno = MESHLINK_EINVAL;
1532 meshlink_node_t *node = NULL;
1534 pthread_mutex_lock(&(mesh->mesh_mutex));
1535 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1536 pthread_mutex_unlock(&(mesh->mesh_mutex));
1540 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1541 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1542 meshlink_errno = MESHLINK_EINVAL;
1546 meshlink_node_t **result;
1549 pthread_mutex_lock(&(mesh->mesh_mutex));
1551 *nmemb = mesh->nodes->count;
1552 result = realloc(nodes, *nmemb * sizeof(*nodes));
1555 meshlink_node_t **p = result;
1557 for splay_each(node_t, n, mesh->nodes) {
1558 *p++ = (meshlink_node_t *)n;
1563 meshlink_errno = MESHLINK_ENOMEM;
1566 pthread_mutex_unlock(&(mesh->mesh_mutex));
1571 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1572 if(!mesh || !data || !len || !signature || !siglen) {
1573 meshlink_errno = MESHLINK_EINVAL;
1577 if(*siglen < MESHLINK_SIGLEN) {
1578 meshlink_errno = MESHLINK_EINVAL;
1582 pthread_mutex_lock(&(mesh->mesh_mutex));
1584 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1585 meshlink_errno = MESHLINK_EINTERNAL;
1586 pthread_mutex_unlock(&(mesh->mesh_mutex));
1590 *siglen = MESHLINK_SIGLEN;
1591 pthread_mutex_unlock(&(mesh->mesh_mutex));
1595 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1596 if(!mesh || !data || !len || !signature) {
1597 meshlink_errno = MESHLINK_EINVAL;
1601 if(siglen != MESHLINK_SIGLEN) {
1602 meshlink_errno = MESHLINK_EINVAL;
1606 pthread_mutex_lock(&(mesh->mesh_mutex));
1610 struct node_t *n = (struct node_t *)source;
1611 node_read_ecdsa_public_key(mesh, n);
1614 meshlink_errno = MESHLINK_EINTERNAL;
1617 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1620 pthread_mutex_unlock(&(mesh->mesh_mutex));
1624 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1625 char filename[PATH_MAX];
1627 pthread_mutex_lock(&(mesh->mesh_mutex));
1629 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1631 if(mkdir(filename, 0700) && errno != EEXIST) {
1632 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1633 meshlink_errno = MESHLINK_ESTORAGE;
1634 pthread_mutex_unlock(&(mesh->mesh_mutex));
1638 // Count the number of valid invitations, clean up old ones
1639 DIR *dir = opendir(filename);
1642 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1643 meshlink_errno = MESHLINK_ESTORAGE;
1644 pthread_mutex_unlock(&(mesh->mesh_mutex));
1651 time_t deadline = time(NULL) - 604800; // 1 week in the past
1653 while((ent = readdir(dir))) {
1654 if(strlen(ent->d_name) != 24) {
1658 char invname[PATH_MAX];
1661 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1662 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1666 if(!stat(invname, &st)) {
1667 if(mesh->invitation_key && deadline < st.st_mtime) {
1673 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1679 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1681 meshlink_errno = MESHLINK_ESTORAGE;
1682 pthread_mutex_unlock(&(mesh->mesh_mutex));
1688 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1690 // Remove the key if there are no outstanding invitations.
1694 if(mesh->invitation_key) {
1695 ecdsa_free(mesh->invitation_key);
1696 mesh->invitation_key = NULL;
1700 if(mesh->invitation_key) {
1701 pthread_mutex_unlock(&(mesh->mesh_mutex));
1705 // Create a new key if necessary.
1706 FILE *f = fopen(filename, "rb");
1709 if(errno != ENOENT) {
1710 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1711 meshlink_errno = MESHLINK_ESTORAGE;
1712 pthread_mutex_unlock(&(mesh->mesh_mutex));
1716 mesh->invitation_key = ecdsa_generate();
1718 if(!mesh->invitation_key) {
1719 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1720 meshlink_errno = MESHLINK_EINTERNAL;
1721 pthread_mutex_unlock(&(mesh->mesh_mutex));
1725 f = fopen(filename, "wb");
1728 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1729 meshlink_errno = MESHLINK_ESTORAGE;
1730 pthread_mutex_unlock(&(mesh->mesh_mutex));
1734 chmod(filename, 0600);
1735 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1738 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1741 if(!mesh->invitation_key) {
1742 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1743 meshlink_errno = MESHLINK_ESTORAGE;
1747 pthread_mutex_unlock(&(mesh->mesh_mutex));
1748 return mesh->invitation_key;
1751 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1752 if(!mesh || !node || !address) {
1753 meshlink_errno = MESHLINK_EINVAL;
1757 if(!is_valid_hostname(address)) {
1758 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1759 meshlink_errno = MESHLINK_EINVAL;
1763 if(port && !is_valid_port(port)) {
1764 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1765 meshlink_errno = MESHLINK_EINVAL;
1769 char *canonical_address;
1772 xasprintf(&canonical_address, "%s %s", address, port);
1774 canonical_address = xstrdup(address);
1777 pthread_mutex_lock(&(mesh->mesh_mutex));
1778 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1779 pthread_mutex_unlock(&(mesh->mesh_mutex));
1781 free(canonical_address);
1785 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1786 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1789 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1791 meshlink_errno = MESHLINK_EINVAL;
1795 char *address = meshlink_get_external_address(mesh);
1803 pthread_mutex_lock(&(mesh->mesh_mutex));
1804 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1805 pthread_mutex_unlock(&(mesh->mesh_mutex));
1811 int meshlink_get_port(meshlink_handle_t *mesh) {
1813 meshlink_errno = MESHLINK_EINVAL;
1818 meshlink_errno = MESHLINK_EINTERNAL;
1822 return atoi(mesh->myport);
1825 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1826 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1827 meshlink_errno = MESHLINK_EINVAL;
1831 if(mesh->myport && port == atoi(mesh->myport)) {
1835 if(!try_bind(port)) {
1836 meshlink_errno = MESHLINK_ENETWORK;
1842 pthread_mutex_lock(&(mesh->mesh_mutex));
1844 if(mesh->threadstarted) {
1845 meshlink_errno = MESHLINK_EINVAL;
1849 close_network_connections(mesh);
1850 exit_configuration(&mesh->config);
1853 snprintf(portstr, sizeof(portstr), "%d", port);
1854 portstr[sizeof(portstr) - 1] = 0;
1856 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1858 init_configuration(&mesh->config);
1860 if(!read_server_config(mesh)) {
1861 meshlink_errno = MESHLINK_ESTORAGE;
1862 } else if(!setup_network(mesh)) {
1863 meshlink_errno = MESHLINK_ENETWORK;
1869 pthread_mutex_unlock(&(mesh->mesh_mutex));
1874 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1875 mesh->invitation_timeout = timeout;
1878 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1880 meshlink_errno = MESHLINK_EINVAL;
1884 pthread_mutex_lock(&(mesh->mesh_mutex));
1886 // Check validity of the new node's name
1887 if(!check_id(name)) {
1888 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1889 meshlink_errno = MESHLINK_EINVAL;
1890 pthread_mutex_unlock(&(mesh->mesh_mutex));
1894 // Ensure no host configuration file with that name exists
1895 char filename[PATH_MAX];
1896 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1898 if(!access(filename, F_OK)) {
1899 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1900 meshlink_errno = MESHLINK_EEXIST;
1901 pthread_mutex_unlock(&(mesh->mesh_mutex));
1905 // Ensure no other nodes know about this name
1906 if(meshlink_get_node(mesh, name)) {
1907 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1908 meshlink_errno = MESHLINK_EEXIST;
1909 pthread_mutex_unlock(&(mesh->mesh_mutex));
1913 // Get the local address
1914 char *address = get_my_hostname(mesh);
1917 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1918 meshlink_errno = MESHLINK_ERESOLV;
1919 pthread_mutex_unlock(&(mesh->mesh_mutex));
1923 if(!refresh_invitation_key(mesh)) {
1924 meshlink_errno = MESHLINK_EINTERNAL;
1925 pthread_mutex_unlock(&(mesh->mesh_mutex));
1931 // Create a hash of the key.
1932 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1933 sha512(fingerprint, strlen(fingerprint), hash);
1934 b64encode_urlsafe(hash, hash, 18);
1936 // Create a random cookie for this invitation.
1938 randomize(cookie, 18);
1940 // Create a filename that doesn't reveal the cookie itself
1941 char buf[18 + strlen(fingerprint)];
1942 char cookiehash[64];
1943 memcpy(buf, cookie, 18);
1944 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1945 sha512(buf, sizeof(buf), cookiehash);
1946 b64encode_urlsafe(cookiehash, cookiehash, 18);
1948 b64encode_urlsafe(cookie, cookie, 18);
1952 // Create a file containing the details of the invitation.
1953 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1954 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1957 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1958 meshlink_errno = MESHLINK_ESTORAGE;
1959 pthread_mutex_unlock(&(mesh->mesh_mutex));
1963 FILE *f = fdopen(ifd, "w");
1969 // Fill in the details.
1970 fprintf(f, "Name = %s\n", name);
1971 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1973 // Copy Broadcast and Mode
1974 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1975 FILE *tc = fopen(filename, "r");
1980 while(fgets(buf, sizeof(buf), tc)) {
1981 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1982 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1985 // Make sure there is a newline character.
1986 if(!strchr(buf, '\n')) {
1994 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1995 meshlink_errno = MESHLINK_ESTORAGE;
1996 pthread_mutex_unlock(&(mesh->mesh_mutex));
2000 fprintf(f, "#---------------------------------------------------------------#\n");
2001 fprintf(f, "Name = %s\n", mesh->self->name);
2003 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2007 // Create an URL from the local address, key hash and cookie
2009 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2012 pthread_mutex_unlock(&(mesh->mesh_mutex));
2016 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2017 if(!mesh || !invitation) {
2018 meshlink_errno = MESHLINK_EINVAL;
2022 pthread_mutex_lock(&(mesh->mesh_mutex));
2024 //Before doing meshlink_join make sure we are not connected to another mesh
2025 if(mesh->threadstarted) {
2026 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2027 meshlink_errno = MESHLINK_EINVAL;
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2032 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2033 char copy[strlen(invitation) + 1];
2034 strcpy(copy, invitation);
2036 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2038 char *slash = strchr(copy, '/');
2046 if(strlen(slash) != 48) {
2050 char *address = copy;
2053 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2057 // Generate a throw-away key for the invitation.
2058 ecdsa_t *key = ecdsa_generate();
2061 meshlink_errno = MESHLINK_EINTERNAL;
2062 pthread_mutex_unlock(&(mesh->mesh_mutex));
2066 char *b64key = ecdsa_get_base64_public_key(key);
2070 while(address && *address) {
2071 // We allow commas in the address part to support multiple addresses in one invitation URL.
2072 comma = strchr(address, ',');
2078 // Split of the port
2079 port = strrchr(address, ':');
2087 // IPv6 address are enclosed in brackets, per RFC 3986
2088 if(*address == '[') {
2090 char *bracket = strchr(address, ']');
2103 // Connect to the meshlink daemon mentioned in the URL.
2104 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2107 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2108 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2110 if(mesh->sock == -1) {
2111 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2112 meshlink_errno = MESHLINK_ENETWORK;
2116 set_timeout(mesh->sock, 5000);
2118 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2119 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2120 meshlink_errno = MESHLINK_ENETWORK;
2121 closesocket(mesh->sock);
2129 meshlink_errno = MESHLINK_ERESOLV;
2132 if(mesh->sock != -1 || !comma) {
2139 if(mesh->sock == -1) {
2140 pthread_mutex_unlock(&mesh->mesh_mutex);
2144 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2146 // Tell him we have an invitation, and give him our throw-away key.
2150 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2151 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2152 closesocket(mesh->sock);
2153 meshlink_errno = MESHLINK_ENETWORK;
2154 pthread_mutex_unlock(&(mesh->mesh_mutex));
2160 char hisname[4096] = "";
2161 int code, hismajor, hisminor = 0;
2163 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) {
2164 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2165 closesocket(mesh->sock);
2166 meshlink_errno = MESHLINK_ENETWORK;
2167 pthread_mutex_unlock(&(mesh->mesh_mutex));
2171 // Check if the hash of the key he gave us matches the hash in the URL.
2172 char *fingerprint = mesh->line + 2;
2175 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2176 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2177 meshlink_errno = MESHLINK_EINTERNAL;
2178 pthread_mutex_unlock(&(mesh->mesh_mutex));
2182 if(memcmp(hishash, mesh->hash, 18)) {
2183 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2184 meshlink_errno = MESHLINK_EPEER;
2185 pthread_mutex_unlock(&(mesh->mesh_mutex));
2190 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2193 meshlink_errno = MESHLINK_EINTERNAL;
2194 pthread_mutex_unlock(&(mesh->mesh_mutex));
2198 // Start an SPTPS session
2199 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2200 meshlink_errno = MESHLINK_EINTERNAL;
2201 pthread_mutex_unlock(&(mesh->mesh_mutex));
2205 // Feed rest of input buffer to SPTPS
2206 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2207 meshlink_errno = MESHLINK_EPEER;
2208 pthread_mutex_unlock(&(mesh->mesh_mutex));
2214 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2216 if(errno == EINTR) {
2220 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2221 meshlink_errno = MESHLINK_ENETWORK;
2222 pthread_mutex_unlock(&(mesh->mesh_mutex));
2226 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2227 meshlink_errno = MESHLINK_EPEER;
2228 pthread_mutex_unlock(&(mesh->mesh_mutex));
2233 sptps_stop(&mesh->sptps);
2236 closesocket(mesh->sock);
2238 if(!mesh->success) {
2239 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2240 meshlink_errno = MESHLINK_EPEER;
2241 pthread_mutex_unlock(&(mesh->mesh_mutex));
2245 pthread_mutex_unlock(&(mesh->mesh_mutex));
2249 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2250 meshlink_errno = MESHLINK_EINVAL;
2251 pthread_mutex_unlock(&(mesh->mesh_mutex));
2255 char *meshlink_export(meshlink_handle_t *mesh) {
2257 meshlink_errno = MESHLINK_EINVAL;
2261 pthread_mutex_lock(&(mesh->mesh_mutex));
2263 char filename[PATH_MAX];
2264 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2265 FILE *f = fopen(filename, "r");
2268 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2269 meshlink_errno = MESHLINK_ESTORAGE;
2270 pthread_mutex_unlock(&(mesh->mesh_mutex));
2274 fseek(f, 0, SEEK_END);
2275 int fsize = ftell(f);
2278 size_t len = fsize + 9 + strlen(mesh->self->name);
2279 char *buf = xmalloc(len);
2280 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2282 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2283 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2286 meshlink_errno = MESHLINK_ESTORAGE;
2287 pthread_mutex_unlock(&(mesh->mesh_mutex));
2294 pthread_mutex_unlock(&(mesh->mesh_mutex));
2298 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2299 if(!mesh || !data) {
2300 meshlink_errno = MESHLINK_EINVAL;
2304 pthread_mutex_lock(&(mesh->mesh_mutex));
2306 if(strncmp(data, "Name = ", 7)) {
2307 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2308 meshlink_errno = MESHLINK_EPEER;
2309 pthread_mutex_unlock(&(mesh->mesh_mutex));
2313 char *end = strchr(data + 7, '\n');
2316 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2317 meshlink_errno = MESHLINK_EPEER;
2318 pthread_mutex_unlock(&(mesh->mesh_mutex));
2322 int len = end - (data + 7);
2324 memcpy(name, data + 7, len);
2327 if(!check_id(name)) {
2328 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2329 meshlink_errno = MESHLINK_EPEER;
2330 pthread_mutex_unlock(&(mesh->mesh_mutex));
2334 char filename[PATH_MAX];
2335 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2337 if(!access(filename, F_OK)) {
2338 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2339 meshlink_errno = MESHLINK_EEXIST;
2340 pthread_mutex_unlock(&(mesh->mesh_mutex));
2344 if(errno != ENOENT) {
2345 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2346 meshlink_errno = MESHLINK_ESTORAGE;
2347 pthread_mutex_unlock(&(mesh->mesh_mutex));
2351 FILE *f = fopen(filename, "w");
2354 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2355 meshlink_errno = MESHLINK_ESTORAGE;
2356 pthread_mutex_unlock(&(mesh->mesh_mutex));
2360 fwrite(end + 1, strlen(end + 1), 1, f);
2363 load_all_nodes(mesh);
2365 pthread_mutex_unlock(&(mesh->mesh_mutex));
2369 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2370 if(!mesh || !node) {
2371 meshlink_errno = MESHLINK_EINVAL;
2375 pthread_mutex_lock(&(mesh->mesh_mutex));
2379 n->status.blacklisted = true;
2380 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2382 //Make blacklisting persistent in the config file
2383 append_config_file(mesh, n->name, "blacklisted", "yes");
2385 //Immediately terminate any connections we have with the blacklisted node
2386 for list_each(connection_t, c, mesh->connections) {
2388 terminate_connection(mesh, c, c->status.active);
2392 pthread_mutex_unlock(&(mesh->mesh_mutex));
2395 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2396 if(!mesh || !node) {
2397 meshlink_errno = MESHLINK_EINVAL;
2401 pthread_mutex_lock(&(mesh->mesh_mutex));
2403 node_t *n = (node_t *)node;
2404 n->status.blacklisted = false;
2406 //TODO: remove blacklisted = yes from the config file
2408 pthread_mutex_unlock(&(mesh->mesh_mutex));
2412 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2413 mesh->default_blacklist = blacklist;
2416 /* Hint that a hostname may be found at an address
2417 * See header file for detailed comment.
2419 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2420 if(!mesh || !node || !addr) {
2424 // Ignore hints about ourself.
2425 if((node_t *)node == mesh->self) {
2429 pthread_mutex_lock(&(mesh->mesh_mutex));
2431 char *host = NULL, *port = NULL, *str = NULL;
2432 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2435 xasprintf(&str, "%s %s", host, port);
2437 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2438 modify_config_file(mesh, node->name, "Address", str, 5);
2440 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2448 pthread_mutex_unlock(&(mesh->mesh_mutex));
2449 // @TODO do we want to fire off a connection attempt right away?
2452 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2454 node_t *n = utcp->priv;
2455 meshlink_handle_t *mesh = n->mesh;
2456 return mesh->channel_accept_cb;
2459 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2460 meshlink_channel_t *channel = connection->priv;
2466 node_t *n = channel->node;
2467 meshlink_handle_t *mesh = n->mesh;
2469 if(n->status.destroyed) {
2470 meshlink_channel_close(mesh, channel);
2471 } else if(channel->receive_cb) {
2472 channel->receive_cb(mesh, channel, data, len);
2478 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2479 node_t *n = utcp_connection->utcp->priv;
2485 meshlink_handle_t *mesh = n->mesh;
2487 if(!mesh->channel_accept_cb) {
2491 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2493 channel->c = utcp_connection;
2495 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2496 utcp_accept(utcp_connection, channel_recv, channel);
2502 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2503 node_t *n = utcp->priv;
2505 if(n->status.destroyed) {
2509 meshlink_handle_t *mesh = n->mesh;
2510 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2513 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2514 if(!mesh || !channel) {
2515 meshlink_errno = MESHLINK_EINVAL;
2519 channel->receive_cb = cb;
2522 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2524 node_t *n = (node_t *)source;
2530 utcp_recv(n->utcp, data, len);
2533 static void channel_poll(struct utcp_connection *connection, size_t len) {
2534 meshlink_channel_t *channel = connection->priv;
2540 node_t *n = channel->node;
2541 meshlink_handle_t *mesh = n->mesh;
2543 if(channel->poll_cb) {
2544 channel->poll_cb(mesh, channel, len);
2548 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2550 channel->poll_cb = cb;
2551 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2554 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2556 meshlink_errno = MESHLINK_EINVAL;
2560 pthread_mutex_lock(&mesh->mesh_mutex);
2561 mesh->channel_accept_cb = cb;
2562 mesh->receive_cb = channel_receive;
2564 for splay_each(node_t, n, mesh->nodes) {
2565 if(!n->utcp && n != mesh->self) {
2566 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2570 pthread_mutex_unlock(&mesh->mesh_mutex);
2573 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) {
2575 abort(); // TODO: handle non-NULL data
2578 if(!mesh || !node) {
2579 meshlink_errno = MESHLINK_EINVAL;
2583 node_t *n = (node_t *)node;
2586 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2587 mesh->receive_cb = channel_receive;
2590 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2595 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2597 channel->receive_cb = cb;
2598 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2601 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2609 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) {
2610 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2613 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2614 if(!mesh || !channel) {
2615 meshlink_errno = MESHLINK_EINVAL;
2619 utcp_shutdown(channel->c, direction);
2622 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2623 if(!mesh || !channel) {
2624 meshlink_errno = MESHLINK_EINVAL;
2628 utcp_close(channel->c);
2632 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2633 if(!mesh || !channel) {
2634 meshlink_errno = MESHLINK_EINVAL;
2643 meshlink_errno = MESHLINK_EINVAL;
2647 // TODO: more finegrained locking.
2648 // Ideally we want to put the data into the UTCP connection's send buffer.
2649 // Then, preferrably only if there is room in the receiver window,
2650 // kick the meshlink thread to go send packets.
2652 pthread_mutex_lock(&mesh->mesh_mutex);
2653 ssize_t retval = utcp_send(channel->c, data, len);
2654 pthread_mutex_unlock(&mesh->mesh_mutex);
2657 meshlink_errno = MESHLINK_ENETWORK;
2663 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2664 if(!mesh || !channel) {
2665 meshlink_errno = MESHLINK_EINVAL;
2669 return channel->c->flags;
2672 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2673 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2674 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2677 if(mesh->node_status_cb) {
2678 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2682 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2683 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2687 n->status.duplicate = true;
2688 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2691 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2695 meshlink_errno = MESHLINK_EINVAL;
2699 pthread_mutex_lock(&mesh->mesh_mutex);
2701 if(mesh->discovery == enable) {
2705 if(mesh->threadstarted) {
2707 discovery_start(mesh);
2709 discovery_stop(mesh);
2713 mesh->discovery = enable;
2716 pthread_mutex_unlock(&mesh->mesh_mutex);
2720 meshlink_errno = MESHLINK_ENOTSUP;
2724 static void __attribute__((constructor)) meshlink_init(void) {
2727 randomize(&seed, sizeof(seed));
2731 static void __attribute__((destructor)) meshlink_exit(void) {
2735 /// Device class traits
2736 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2737 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2738 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2739 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2740 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN