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 // This gets the hostname part for use in invitation URLs
351 static char *get_my_hostname(meshlink_handle_t *mesh) {
352 char *hostname[2] = {NULL};
354 char *hostport = NULL;
355 char *name = mesh->self->name;
356 char filename[PATH_MAX] = "";
358 // Use first Address statement in own host config file
359 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
360 scan_for_hostname(filename, &hostname[0], &port);
366 hostname[0] = meshlink_get_external_address_for_family(mesh, AF_INET);
367 hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET6);
369 if(!hostname[0] && !hostname[1]) {
373 if(hostname[0] && hostname[1] && !strcmp(hostname[0], hostname[1])) {
378 port = xstrdup(mesh->myport);
380 for(int i = 0; i < 2; i++) {
383 xasprintf(&tmphostport, "%s %s", hostname[i], port);
384 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
391 for(int i = 0; i < 2; i++) {
397 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]" : "%s%s%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i]);
400 hostport = newhostport;
405 xasprintf(&newhostport, "%s:%s", hostport, port);
408 hostport = newhostport;
414 static char *get_line(const char **data) {
415 if(!data || !*data) {
424 static char line[1024];
425 const char *end = strchr(*data, '\n');
426 size_t len = end ? (size_t)(end - *data) : strlen(*data);
428 if(len >= sizeof(line)) {
429 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
433 if(len && !isprint(**data)) {
437 memcpy(line, *data, len);
449 static char *get_value(const char *data, const char *var) {
450 char *line = get_line(&data);
456 char *sep = line + strcspn(line, " \t=");
457 char *val = sep + strspn(sep, " \t");
460 val += 1 + strspn(val + 1, " \t");
465 if(strcasecmp(line, var)) {
472 static bool try_bind(int port) {
473 struct addrinfo *ai = NULL;
474 struct addrinfo hint = {
475 .ai_flags = AI_PASSIVE,
476 .ai_family = AF_UNSPEC,
477 .ai_socktype = SOCK_STREAM,
478 .ai_protocol = IPPROTO_TCP,
482 snprintf(portstr, sizeof(portstr), "%d", port);
484 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
489 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
496 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
511 int check_port(meshlink_handle_t *mesh) {
512 for(int i = 0; i < 1000; i++) {
513 int port = 0x1000 + (rand() & 0x7fff);
516 char filename[PATH_MAX];
517 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
518 FILE *f = fopen(filename, "a");
521 meshlink_errno = MESHLINK_ESTORAGE;
522 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
526 fprintf(f, "Port = %d\n", port);
532 meshlink_errno = MESHLINK_ENETWORK;
533 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
537 static void deltree(const char *dirname) {
538 DIR *d = opendir(dirname);
543 while((ent = readdir(d))) {
544 if(ent->d_name[0] == '.') {
548 char filename[PATH_MAX];
549 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
551 if(unlink(filename)) {
562 static bool finalize_join(meshlink_handle_t *mesh) {
563 char *name = xstrdup(get_value(mesh->data, "Name"));
566 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
570 if(!check_id(name)) {
571 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
575 char filename[PATH_MAX];
576 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
578 FILE *f = fopen(filename, "w");
581 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
585 fprintf(f, "Name = %s\n", name);
587 // Wipe all old host config files and invitations
588 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
591 if(mkdir(filename, 0777) && errno != EEXIST) {
592 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
596 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
599 // Create a new host config file for ourself
600 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
601 FILE *fh = fopen(filename, "w");
604 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
609 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
610 // Other chunks go unfiltered to their respective host config files
611 const char *p = mesh->data;
614 while((l = get_line(&p))) {
620 // Split line into variable and value
621 int len = strcspn(l, "\t =");
623 value += strspn(value, "\t ");
627 value += strspn(value, "\t ");
633 if(!strcasecmp(l, "Name"))
634 if(strcmp(value, name)) {
638 } else if(!strcasecmp(l, "NetName")) {
642 // Check the list of known variables
646 for(i = 0; variables[i].name; i++) {
647 if(strcasecmp(l, variables[i].name)) {
655 // Ignore unknown and unsafe variables
657 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
659 } else if(!(variables[i].type & VAR_SAFE)) {
660 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
664 // Copy the safe variable to the right config file
665 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
670 while(l && !strcasecmp(l, "Name")) {
671 if(!check_id(value)) {
672 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
676 if(!strcmp(value, name)) {
677 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
681 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
682 f = fopen(filename, "w");
685 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
689 while((l = get_line(&p))) {
690 if(!strcmp(l, "#---------------------------------------------------------------#")) {
694 int len = strcspn(l, "\t =");
696 if(len == 4 && !strncasecmp(l, "Name", 4)) {
698 value += strspn(value, "\t ");
702 value += strspn(value, "\t ");
716 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
723 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
724 fprintf(fh, "Port = %s\n", mesh->myport);
728 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
732 free(mesh->self->name);
733 free(mesh->self->connection->name);
734 mesh->name = xstrdup(name);
735 mesh->self->name = xstrdup(name);
736 mesh->self->connection->name = name;
738 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
740 load_all_nodes(mesh);
745 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
747 meshlink_handle_t *mesh = handle;
748 const char *ptr = data;
751 int result = send(mesh->sock, ptr, len, 0);
753 if(result == -1 && errno == EINTR) {
755 } else if(result <= 0) {
766 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
767 meshlink_handle_t *mesh = handle;
770 case SPTPS_HANDSHAKE:
771 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
774 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
775 memcpy(mesh->data + mesh->thedatalen, msg, len);
776 mesh->thedatalen += len;
777 mesh->data[mesh->thedatalen] = 0;
781 mesh->thedatalen = 0;
782 return finalize_join(mesh);
785 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
786 shutdown(mesh->sock, SHUT_RDWR);
787 mesh->success = true;
797 static bool recvline(meshlink_handle_t *mesh, size_t len) {
798 char *newline = NULL;
804 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
805 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
807 if(result == -1 && errno == EINTR) {
809 } else if(result <= 0) {
813 mesh->blen += result;
816 if((size_t)(newline - mesh->buffer) >= len) {
820 len = newline - mesh->buffer;
822 memcpy(mesh->line, mesh->buffer, len);
824 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
825 mesh->blen -= len + 1;
829 static bool sendline(int fd, char *format, ...) {
830 static char buffer[4096];
835 va_start(ap, format);
836 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
839 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
847 int result = send(fd, p, blen, MSG_NOSIGNAL);
849 if(result == -1 && errno == EINTR) {
851 } else if(result <= 0) {
862 static const char *errstr[] = {
863 [MESHLINK_OK] = "No error",
864 [MESHLINK_EINVAL] = "Invalid argument",
865 [MESHLINK_ENOMEM] = "Out of memory",
866 [MESHLINK_ENOENT] = "No such node",
867 [MESHLINK_EEXIST] = "Node already exists",
868 [MESHLINK_EINTERNAL] = "Internal error",
869 [MESHLINK_ERESOLV] = "Could not resolve hostname",
870 [MESHLINK_ESTORAGE] = "Storage error",
871 [MESHLINK_ENETWORK] = "Network error",
872 [MESHLINK_EPEER] = "Error communicating with peer",
875 const char *meshlink_strerror(meshlink_errno_t err) {
876 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
877 return "Invalid error code";
883 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
886 char pubname[PATH_MAX], privname[PATH_MAX];
888 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
890 if(!(key = ecdsa_generate())) {
891 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
892 meshlink_errno = MESHLINK_EINTERNAL;
895 logger(mesh, MESHLINK_DEBUG, "Done.\n");
898 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
899 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
900 meshlink_errno = MESHLINK_ESTORAGE;
904 f = fopen(privname, "wb");
907 meshlink_errno = MESHLINK_ESTORAGE;
912 fchmod(fileno(f), 0600);
915 if(!ecdsa_write_pem_private_key(key, f)) {
916 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
919 meshlink_errno = MESHLINK_EINTERNAL;
925 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
926 f = fopen(pubname, "a");
929 meshlink_errno = MESHLINK_ESTORAGE;
933 char *pubkey = ecdsa_get_base64_public_key(key);
934 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
943 static struct timeval idle(event_loop_t *loop, void *data) {
945 meshlink_handle_t *mesh = data;
946 struct timeval t, tmin = {3600, 0};
948 for splay_each(node_t, n, mesh->nodes) {
953 t = utcp_timeout(n->utcp);
955 if(timercmp(&t, &tmin, <)) {
963 // Get our local address(es) by simulating connecting to an Internet host.
964 static void add_local_addresses(meshlink_handle_t *mesh) {
965 char host[NI_MAXHOST];
966 char entry[MAX_STRING_SIZE];
970 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
971 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
972 append_config_file(mesh, mesh->name, "Address", entry);
977 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
978 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
979 append_config_file(mesh, mesh->name, "Address", entry);
983 static bool meshlink_setup(meshlink_handle_t *mesh) {
984 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
985 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
986 meshlink_errno = MESHLINK_ESTORAGE;
990 char filename[PATH_MAX];
991 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
993 if(mkdir(filename, 0777) && errno != EEXIST) {
994 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
995 meshlink_errno = MESHLINK_ESTORAGE;
999 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1001 if(!access(filename, F_OK)) {
1002 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1003 meshlink_errno = MESHLINK_EEXIST;
1007 FILE *f = fopen(filename, "w");
1010 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1011 meshlink_errno = MESHLINK_ESTORAGE;
1015 fprintf(f, "Name = %s\n", mesh->name);
1018 if(!ecdsa_keygen(mesh)) {
1019 meshlink_errno = MESHLINK_EINTERNAL;
1024 if(check_port(mesh) == 0) {
1025 meshlink_errno = MESHLINK_ENETWORK;
1033 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1034 // Validate arguments provided by the application
1035 bool usingname = false;
1037 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1039 if(!confbase || !*confbase) {
1040 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1041 meshlink_errno = MESHLINK_EINVAL;
1045 if(!appname || !*appname) {
1046 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1047 meshlink_errno = MESHLINK_EINVAL;
1051 if(strchr(appname, ' ')) {
1052 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1053 meshlink_errno = MESHLINK_EINVAL;
1057 if(!name || !*name) {
1058 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1060 } else { //check name only if there is a name != NULL
1062 if(!check_id(name)) {
1063 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1064 meshlink_errno = MESHLINK_EINVAL;
1071 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1072 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1073 meshlink_errno = MESHLINK_EINVAL;
1077 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1078 mesh->confbase = xstrdup(confbase);
1079 mesh->appname = xstrdup(appname);
1080 mesh->devclass = devclass;
1081 mesh->discovery = true;
1082 mesh->invitation_timeout = 604800; // 1 week
1085 mesh->name = xstrdup(name);
1089 pthread_mutexattr_t attr;
1090 pthread_mutexattr_init(&attr);
1091 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1092 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1094 mesh->threadstarted = false;
1095 event_loop_init(&mesh->loop);
1096 mesh->loop.data = mesh;
1098 meshlink_queue_init(&mesh->outpacketqueue);
1100 // Check whether meshlink.conf already exists
1102 char filename[PATH_MAX];
1103 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1105 if(access(filename, R_OK)) {
1106 if(errno == ENOENT) {
1107 // If not, create it
1108 if(!meshlink_setup(mesh)) {
1109 // meshlink_errno is set by meshlink_setup()
1113 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1114 meshlink_close(mesh);
1115 meshlink_errno = MESHLINK_ESTORAGE;
1120 // Read the configuration
1122 init_configuration(&mesh->config);
1124 if(!read_server_config(mesh)) {
1125 meshlink_close(mesh);
1126 meshlink_errno = MESHLINK_ESTORAGE;
1131 struct WSAData wsa_state;
1133 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1137 // Setup up everything
1138 // TODO: we should not open listening sockets yet
1140 if(!setup_network(mesh)) {
1141 meshlink_close(mesh);
1142 meshlink_errno = MESHLINK_ENETWORK;
1146 add_local_addresses(mesh);
1148 idle_set(&mesh->loop, idle, mesh);
1150 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1154 static void *meshlink_main_loop(void *arg) {
1155 meshlink_handle_t *mesh = arg;
1157 pthread_mutex_lock(&(mesh->mesh_mutex));
1159 try_outgoing_connections(mesh);
1161 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1163 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1165 pthread_mutex_unlock(&(mesh->mesh_mutex));
1169 bool meshlink_start(meshlink_handle_t *mesh) {
1171 meshlink_errno = MESHLINK_EINVAL;
1175 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1177 pthread_mutex_lock(&(mesh->mesh_mutex));
1179 if(mesh->threadstarted) {
1180 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1181 pthread_mutex_unlock(&(mesh->mesh_mutex));
1185 if(mesh->listen_socket[0].tcp.fd < 0) {
1186 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1187 meshlink_errno = MESHLINK_ENETWORK;
1191 mesh->thedatalen = 0;
1193 // TODO: open listening sockets first
1195 //Check that a valid name is set
1197 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1198 meshlink_errno = MESHLINK_EINVAL;
1199 pthread_mutex_unlock(&(mesh->mesh_mutex));
1203 // Start the main thread
1205 event_loop_start(&mesh->loop);
1207 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1208 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1209 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1210 meshlink_errno = MESHLINK_EINTERNAL;
1211 event_loop_stop(&mesh->loop);
1212 pthread_mutex_unlock(&(mesh->mesh_mutex));
1216 mesh->threadstarted = true;
1220 if(mesh->discovery) {
1221 discovery_start(mesh);
1226 pthread_mutex_unlock(&(mesh->mesh_mutex));
1230 void meshlink_stop(meshlink_handle_t *mesh) {
1232 meshlink_errno = MESHLINK_EINVAL;
1236 pthread_mutex_lock(&(mesh->mesh_mutex));
1237 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1242 if(mesh->discovery) {
1243 discovery_stop(mesh);
1248 // Shut down the main thread
1249 event_loop_stop(&mesh->loop);
1251 // Send ourselves a UDP packet to kick the event loop
1252 for(int i = 0; i < mesh->listen_sockets; i++) {
1254 socklen_t salen = sizeof(sa.sa);
1256 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1257 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1261 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1262 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1266 if(mesh->threadstarted) {
1267 // Wait for the main thread to finish
1268 pthread_mutex_unlock(&(mesh->mesh_mutex));
1269 pthread_join(mesh->thread, NULL);
1270 pthread_mutex_lock(&(mesh->mesh_mutex));
1272 mesh->threadstarted = false;
1275 // Close all metaconnections
1276 if(mesh->connections) {
1277 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1279 connection_t *c = node->data;
1281 terminate_connection(mesh, c, false);
1285 if(mesh->outgoings) {
1286 list_delete_list(mesh->outgoings);
1287 mesh->outgoings = NULL;
1290 pthread_mutex_unlock(&(mesh->mesh_mutex));
1293 void meshlink_close(meshlink_handle_t *mesh) {
1294 if(!mesh || !mesh->confbase) {
1295 meshlink_errno = MESHLINK_EINVAL;
1299 // stop can be called even if mesh has not been started
1300 meshlink_stop(mesh);
1302 // lock is not released after this
1303 pthread_mutex_lock(&(mesh->mesh_mutex));
1305 // Close and free all resources used.
1307 close_network_connections(mesh);
1309 logger(mesh, MESHLINK_INFO, "Terminating");
1311 exit_configuration(&mesh->config);
1312 event_loop_exit(&mesh->loop);
1316 if(mesh->confbase) {
1322 ecdsa_free(mesh->invitation_key);
1325 free(mesh->appname);
1326 free(mesh->confbase);
1327 pthread_mutex_destroy(&(mesh->mesh_mutex));
1329 memset(mesh, 0, sizeof(*mesh));
1334 bool meshlink_destroy(const char *confbase) {
1336 meshlink_errno = MESHLINK_EINVAL;
1340 char filename[PATH_MAX];
1341 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1343 if(unlink(filename)) {
1344 if(errno == ENOENT) {
1345 meshlink_errno = MESHLINK_ENOENT;
1348 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1349 meshlink_errno = MESHLINK_ESTORAGE;
1359 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1361 meshlink_errno = MESHLINK_EINVAL;
1365 pthread_mutex_lock(&(mesh->mesh_mutex));
1366 mesh->receive_cb = cb;
1367 pthread_mutex_unlock(&(mesh->mesh_mutex));
1370 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1372 meshlink_errno = MESHLINK_EINVAL;
1376 pthread_mutex_lock(&(mesh->mesh_mutex));
1377 mesh->node_status_cb = cb;
1378 pthread_mutex_unlock(&(mesh->mesh_mutex));
1381 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1383 meshlink_errno = MESHLINK_EINVAL;
1387 pthread_mutex_lock(&(mesh->mesh_mutex));
1388 mesh->node_duplicate_cb = cb;
1389 pthread_mutex_unlock(&(mesh->mesh_mutex));
1392 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1394 pthread_mutex_lock(&(mesh->mesh_mutex));
1396 mesh->log_level = cb ? level : 0;
1397 pthread_mutex_unlock(&(mesh->mesh_mutex));
1400 global_log_level = cb ? level : 0;
1404 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1405 meshlink_packethdr_t *hdr;
1407 // Validate arguments
1408 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1409 meshlink_errno = MESHLINK_EINVAL;
1418 meshlink_errno = MESHLINK_EINVAL;
1422 // Prepare the packet
1423 vpn_packet_t *packet = malloc(sizeof(*packet));
1426 meshlink_errno = MESHLINK_ENOMEM;
1430 packet->probe = false;
1431 packet->tcp = false;
1432 packet->len = len + sizeof(*hdr);
1434 hdr = (meshlink_packethdr_t *)packet->data;
1435 memset(hdr, 0, sizeof(*hdr));
1436 // leave the last byte as 0 to make sure strings are always
1437 // null-terminated if they are longer than the buffer
1438 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1439 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1441 memcpy(packet->data + sizeof(*hdr), data, len);
1444 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1446 meshlink_errno = MESHLINK_ENOMEM;
1450 // Notify event loop
1451 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1456 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1458 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1464 mesh->self->in_packets++;
1465 mesh->self->in_bytes += packet->len;
1466 route(mesh, mesh->self, packet);
1469 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1470 if(!mesh || !destination) {
1471 meshlink_errno = MESHLINK_EINVAL;
1475 pthread_mutex_lock(&(mesh->mesh_mutex));
1477 node_t *n = (node_t *)destination;
1479 if(!n->status.reachable) {
1480 pthread_mutex_unlock(&(mesh->mesh_mutex));
1483 } else if(n->mtuprobes > 30 && n->minmtu) {
1484 pthread_mutex_unlock(&(mesh->mesh_mutex));
1487 pthread_mutex_unlock(&(mesh->mesh_mutex));
1492 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1493 if(!mesh || !node) {
1494 meshlink_errno = MESHLINK_EINVAL;
1498 pthread_mutex_lock(&(mesh->mesh_mutex));
1500 node_t *n = (node_t *)node;
1502 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1503 meshlink_errno = MESHLINK_EINTERNAL;
1504 pthread_mutex_unlock(&(mesh->mesh_mutex));
1508 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1511 meshlink_errno = MESHLINK_EINTERNAL;
1514 pthread_mutex_unlock(&(mesh->mesh_mutex));
1518 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1520 meshlink_errno = MESHLINK_EINVAL;
1524 return (meshlink_node_t *)mesh->self;
1527 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1528 if(!mesh || !name) {
1529 meshlink_errno = MESHLINK_EINVAL;
1533 meshlink_node_t *node = NULL;
1535 pthread_mutex_lock(&(mesh->mesh_mutex));
1536 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1537 pthread_mutex_unlock(&(mesh->mesh_mutex));
1541 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1542 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1543 meshlink_errno = MESHLINK_EINVAL;
1547 meshlink_node_t **result;
1550 pthread_mutex_lock(&(mesh->mesh_mutex));
1552 *nmemb = mesh->nodes->count;
1553 result = realloc(nodes, *nmemb * sizeof(*nodes));
1556 meshlink_node_t **p = result;
1558 for splay_each(node_t, n, mesh->nodes) {
1559 *p++ = (meshlink_node_t *)n;
1564 meshlink_errno = MESHLINK_ENOMEM;
1567 pthread_mutex_unlock(&(mesh->mesh_mutex));
1572 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1573 if(!mesh || !data || !len || !signature || !siglen) {
1574 meshlink_errno = MESHLINK_EINVAL;
1578 if(*siglen < MESHLINK_SIGLEN) {
1579 meshlink_errno = MESHLINK_EINVAL;
1583 pthread_mutex_lock(&(mesh->mesh_mutex));
1585 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1586 meshlink_errno = MESHLINK_EINTERNAL;
1587 pthread_mutex_unlock(&(mesh->mesh_mutex));
1591 *siglen = MESHLINK_SIGLEN;
1592 pthread_mutex_unlock(&(mesh->mesh_mutex));
1596 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1597 if(!mesh || !data || !len || !signature) {
1598 meshlink_errno = MESHLINK_EINVAL;
1602 if(siglen != MESHLINK_SIGLEN) {
1603 meshlink_errno = MESHLINK_EINVAL;
1607 pthread_mutex_lock(&(mesh->mesh_mutex));
1611 struct node_t *n = (struct node_t *)source;
1612 node_read_ecdsa_public_key(mesh, n);
1615 meshlink_errno = MESHLINK_EINTERNAL;
1618 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1621 pthread_mutex_unlock(&(mesh->mesh_mutex));
1625 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1626 char filename[PATH_MAX];
1628 pthread_mutex_lock(&(mesh->mesh_mutex));
1630 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1632 if(mkdir(filename, 0700) && errno != EEXIST) {
1633 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1634 meshlink_errno = MESHLINK_ESTORAGE;
1635 pthread_mutex_unlock(&(mesh->mesh_mutex));
1639 // Count the number of valid invitations, clean up old ones
1640 DIR *dir = opendir(filename);
1643 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1644 meshlink_errno = MESHLINK_ESTORAGE;
1645 pthread_mutex_unlock(&(mesh->mesh_mutex));
1652 time_t deadline = time(NULL) - 604800; // 1 week in the past
1654 while((ent = readdir(dir))) {
1655 if(strlen(ent->d_name) != 24) {
1659 char invname[PATH_MAX];
1662 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1663 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1667 if(!stat(invname, &st)) {
1668 if(mesh->invitation_key && deadline < st.st_mtime) {
1674 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1680 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1682 meshlink_errno = MESHLINK_ESTORAGE;
1683 pthread_mutex_unlock(&(mesh->mesh_mutex));
1689 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1691 // Remove the key if there are no outstanding invitations.
1695 if(mesh->invitation_key) {
1696 ecdsa_free(mesh->invitation_key);
1697 mesh->invitation_key = NULL;
1701 if(mesh->invitation_key) {
1702 pthread_mutex_unlock(&(mesh->mesh_mutex));
1706 // Create a new key if necessary.
1707 FILE *f = fopen(filename, "rb");
1710 if(errno != ENOENT) {
1711 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1712 meshlink_errno = MESHLINK_ESTORAGE;
1713 pthread_mutex_unlock(&(mesh->mesh_mutex));
1717 mesh->invitation_key = ecdsa_generate();
1719 if(!mesh->invitation_key) {
1720 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1721 meshlink_errno = MESHLINK_EINTERNAL;
1722 pthread_mutex_unlock(&(mesh->mesh_mutex));
1726 f = fopen(filename, "wb");
1729 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1730 meshlink_errno = MESHLINK_ESTORAGE;
1731 pthread_mutex_unlock(&(mesh->mesh_mutex));
1735 chmod(filename, 0600);
1736 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1739 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1742 if(!mesh->invitation_key) {
1743 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1744 meshlink_errno = MESHLINK_ESTORAGE;
1748 pthread_mutex_unlock(&(mesh->mesh_mutex));
1749 return mesh->invitation_key;
1752 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1753 if(!mesh || !node || !address) {
1754 meshlink_errno = MESHLINK_EINVAL;
1758 if(!is_valid_hostname(address)) {
1759 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1760 meshlink_errno = MESHLINK_EINVAL;
1764 if(port && !is_valid_port(port)) {
1765 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1766 meshlink_errno = MESHLINK_EINVAL;
1770 char *canonical_address;
1773 xasprintf(&canonical_address, "%s %s", address, port);
1775 canonical_address = xstrdup(address);
1778 pthread_mutex_lock(&(mesh->mesh_mutex));
1779 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1780 pthread_mutex_unlock(&(mesh->mesh_mutex));
1782 free(canonical_address);
1786 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1787 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1790 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1792 meshlink_errno = MESHLINK_EINVAL;
1796 char *address = meshlink_get_external_address(mesh);
1804 pthread_mutex_lock(&(mesh->mesh_mutex));
1805 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1806 pthread_mutex_unlock(&(mesh->mesh_mutex));
1812 int meshlink_get_port(meshlink_handle_t *mesh) {
1814 meshlink_errno = MESHLINK_EINVAL;
1819 meshlink_errno = MESHLINK_EINTERNAL;
1823 return atoi(mesh->myport);
1826 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1827 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1828 meshlink_errno = MESHLINK_EINVAL;
1832 if(mesh->myport && port == atoi(mesh->myport)) {
1836 if(!try_bind(port)) {
1837 meshlink_errno = MESHLINK_ENETWORK;
1843 pthread_mutex_lock(&(mesh->mesh_mutex));
1845 if(mesh->threadstarted) {
1846 meshlink_errno = MESHLINK_EINVAL;
1850 close_network_connections(mesh);
1851 exit_configuration(&mesh->config);
1854 snprintf(portstr, sizeof(portstr), "%d", port);
1855 portstr[sizeof(portstr) - 1] = 0;
1857 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1859 init_configuration(&mesh->config);
1861 if(!read_server_config(mesh)) {
1862 meshlink_errno = MESHLINK_ESTORAGE;
1863 } else if(!setup_network(mesh)) {
1864 meshlink_errno = MESHLINK_ENETWORK;
1870 pthread_mutex_unlock(&(mesh->mesh_mutex));
1875 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1876 mesh->invitation_timeout = timeout;
1879 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1881 meshlink_errno = MESHLINK_EINVAL;
1885 pthread_mutex_lock(&(mesh->mesh_mutex));
1887 // Check validity of the new node's name
1888 if(!check_id(name)) {
1889 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1890 meshlink_errno = MESHLINK_EINVAL;
1891 pthread_mutex_unlock(&(mesh->mesh_mutex));
1895 // Ensure no host configuration file with that name exists
1896 char filename[PATH_MAX];
1897 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1899 if(!access(filename, F_OK)) {
1900 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1901 meshlink_errno = MESHLINK_EEXIST;
1902 pthread_mutex_unlock(&(mesh->mesh_mutex));
1906 // Ensure no other nodes know about this name
1907 if(meshlink_get_node(mesh, name)) {
1908 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1909 meshlink_errno = MESHLINK_EEXIST;
1910 pthread_mutex_unlock(&(mesh->mesh_mutex));
1914 // Get the local address
1915 char *address = get_my_hostname(mesh);
1918 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1919 meshlink_errno = MESHLINK_ERESOLV;
1920 pthread_mutex_unlock(&(mesh->mesh_mutex));
1924 if(!refresh_invitation_key(mesh)) {
1925 meshlink_errno = MESHLINK_EINTERNAL;
1926 pthread_mutex_unlock(&(mesh->mesh_mutex));
1932 // Create a hash of the key.
1933 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1934 sha512(fingerprint, strlen(fingerprint), hash);
1935 b64encode_urlsafe(hash, hash, 18);
1937 // Create a random cookie for this invitation.
1939 randomize(cookie, 18);
1941 // Create a filename that doesn't reveal the cookie itself
1942 char buf[18 + strlen(fingerprint)];
1943 char cookiehash[64];
1944 memcpy(buf, cookie, 18);
1945 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1946 sha512(buf, sizeof(buf), cookiehash);
1947 b64encode_urlsafe(cookiehash, cookiehash, 18);
1949 b64encode_urlsafe(cookie, cookie, 18);
1953 // Create a file containing the details of the invitation.
1954 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1955 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1958 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1959 meshlink_errno = MESHLINK_ESTORAGE;
1960 pthread_mutex_unlock(&(mesh->mesh_mutex));
1964 FILE *f = fdopen(ifd, "w");
1970 // Fill in the details.
1971 fprintf(f, "Name = %s\n", name);
1972 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1974 // Copy Broadcast and Mode
1975 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1976 FILE *tc = fopen(filename, "r");
1981 while(fgets(buf, sizeof(buf), tc)) {
1982 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1983 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1986 // Make sure there is a newline character.
1987 if(!strchr(buf, '\n')) {
1995 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1996 meshlink_errno = MESHLINK_ESTORAGE;
1997 pthread_mutex_unlock(&(mesh->mesh_mutex));
2001 fprintf(f, "#---------------------------------------------------------------#\n");
2002 fprintf(f, "Name = %s\n", mesh->self->name);
2004 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2008 // Create an URL from the local address, key hash and cookie
2010 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2013 pthread_mutex_unlock(&(mesh->mesh_mutex));
2017 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2018 if(!mesh || !invitation) {
2019 meshlink_errno = MESHLINK_EINVAL;
2023 pthread_mutex_lock(&(mesh->mesh_mutex));
2025 //Before doing meshlink_join make sure we are not connected to another mesh
2026 if(mesh->threadstarted) {
2027 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2028 meshlink_errno = MESHLINK_EINVAL;
2029 pthread_mutex_unlock(&(mesh->mesh_mutex));
2033 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2034 char copy[strlen(invitation) + 1];
2035 strcpy(copy, invitation);
2037 // Split the invitation URL into hostname, port, key hash and cookie.
2039 char *slash = strchr(copy, '/');
2047 if(strlen(slash) != 48) {
2051 char *address = copy;
2052 char *port = strrchr(address, ':');
2060 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2064 // Generate a throw-away key for the invitation.
2065 ecdsa_t *key = ecdsa_generate();
2068 meshlink_errno = MESHLINK_EINTERNAL;
2069 pthread_mutex_unlock(&(mesh->mesh_mutex));
2073 char *b64key = ecdsa_get_base64_public_key(key);
2077 while(address && *address) {
2078 // We allow commas in the address part to support multiple addresses in one invitation URL.
2079 comma = strchr(address, ',');
2085 // IPv6 address are enclosed in brackets, per RFC 3986
2086 if(*address == '[') {
2088 char *bracket = strchr(address, ']');
2096 if(comma && bracket != comma) {
2101 // Connect to the meshlink daemon mentioned in the URL.
2102 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2105 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2106 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2108 if(mesh->sock == -1) {
2109 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2110 meshlink_errno = MESHLINK_ENETWORK;
2114 set_timeout(mesh->sock, 5000);
2116 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2117 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2118 meshlink_errno = MESHLINK_ENETWORK;
2119 closesocket(mesh->sock);
2127 meshlink_errno = MESHLINK_ERESOLV;
2130 if(mesh->sock != -1 || !comma) {
2137 if(mesh->sock == -1) {
2138 pthread_mutex_unlock(&mesh->mesh_mutex);
2142 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2144 // Tell him we have an invitation, and give him our throw-away key.
2148 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2149 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2150 closesocket(mesh->sock);
2151 meshlink_errno = MESHLINK_ENETWORK;
2152 pthread_mutex_unlock(&(mesh->mesh_mutex));
2158 char hisname[4096] = "";
2159 int code, hismajor, hisminor = 0;
2161 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) {
2162 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2163 closesocket(mesh->sock);
2164 meshlink_errno = MESHLINK_ENETWORK;
2165 pthread_mutex_unlock(&(mesh->mesh_mutex));
2169 // Check if the hash of the key he gave us matches the hash in the URL.
2170 char *fingerprint = mesh->line + 2;
2173 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2174 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2175 meshlink_errno = MESHLINK_EINTERNAL;
2176 pthread_mutex_unlock(&(mesh->mesh_mutex));
2180 if(memcmp(hishash, mesh->hash, 18)) {
2181 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2182 meshlink_errno = MESHLINK_EPEER;
2183 pthread_mutex_unlock(&(mesh->mesh_mutex));
2188 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2191 meshlink_errno = MESHLINK_EINTERNAL;
2192 pthread_mutex_unlock(&(mesh->mesh_mutex));
2196 // Start an SPTPS session
2197 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2198 meshlink_errno = MESHLINK_EINTERNAL;
2199 pthread_mutex_unlock(&(mesh->mesh_mutex));
2203 // Feed rest of input buffer to SPTPS
2204 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2205 meshlink_errno = MESHLINK_EPEER;
2206 pthread_mutex_unlock(&(mesh->mesh_mutex));
2212 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2214 if(errno == EINTR) {
2218 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2219 meshlink_errno = MESHLINK_ENETWORK;
2220 pthread_mutex_unlock(&(mesh->mesh_mutex));
2224 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2225 meshlink_errno = MESHLINK_EPEER;
2226 pthread_mutex_unlock(&(mesh->mesh_mutex));
2231 sptps_stop(&mesh->sptps);
2234 closesocket(mesh->sock);
2236 if(!mesh->success) {
2237 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2238 meshlink_errno = MESHLINK_EPEER;
2239 pthread_mutex_unlock(&(mesh->mesh_mutex));
2243 pthread_mutex_unlock(&(mesh->mesh_mutex));
2247 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2248 meshlink_errno = MESHLINK_EINVAL;
2249 pthread_mutex_unlock(&(mesh->mesh_mutex));
2253 char *meshlink_export(meshlink_handle_t *mesh) {
2255 meshlink_errno = MESHLINK_EINVAL;
2259 pthread_mutex_lock(&(mesh->mesh_mutex));
2261 char filename[PATH_MAX];
2262 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2263 FILE *f = fopen(filename, "r");
2266 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2267 meshlink_errno = MESHLINK_ESTORAGE;
2268 pthread_mutex_unlock(&(mesh->mesh_mutex));
2272 fseek(f, 0, SEEK_END);
2273 int fsize = ftell(f);
2276 size_t len = fsize + 9 + strlen(mesh->self->name);
2277 char *buf = xmalloc(len);
2278 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2280 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2281 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2284 meshlink_errno = MESHLINK_ESTORAGE;
2285 pthread_mutex_unlock(&(mesh->mesh_mutex));
2292 pthread_mutex_unlock(&(mesh->mesh_mutex));
2296 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2297 if(!mesh || !data) {
2298 meshlink_errno = MESHLINK_EINVAL;
2302 pthread_mutex_lock(&(mesh->mesh_mutex));
2304 if(strncmp(data, "Name = ", 7)) {
2305 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2306 meshlink_errno = MESHLINK_EPEER;
2307 pthread_mutex_unlock(&(mesh->mesh_mutex));
2311 char *end = strchr(data + 7, '\n');
2314 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2315 meshlink_errno = MESHLINK_EPEER;
2316 pthread_mutex_unlock(&(mesh->mesh_mutex));
2320 int len = end - (data + 7);
2322 memcpy(name, data + 7, len);
2325 if(!check_id(name)) {
2326 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2327 meshlink_errno = MESHLINK_EPEER;
2328 pthread_mutex_unlock(&(mesh->mesh_mutex));
2332 char filename[PATH_MAX];
2333 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2335 if(!access(filename, F_OK)) {
2336 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2337 meshlink_errno = MESHLINK_EEXIST;
2338 pthread_mutex_unlock(&(mesh->mesh_mutex));
2342 if(errno != ENOENT) {
2343 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2344 meshlink_errno = MESHLINK_ESTORAGE;
2345 pthread_mutex_unlock(&(mesh->mesh_mutex));
2349 FILE *f = fopen(filename, "w");
2352 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2353 meshlink_errno = MESHLINK_ESTORAGE;
2354 pthread_mutex_unlock(&(mesh->mesh_mutex));
2358 fwrite(end + 1, strlen(end + 1), 1, f);
2361 load_all_nodes(mesh);
2363 pthread_mutex_unlock(&(mesh->mesh_mutex));
2367 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2368 if(!mesh || !node) {
2369 meshlink_errno = MESHLINK_EINVAL;
2373 pthread_mutex_lock(&(mesh->mesh_mutex));
2377 n->status.blacklisted = true;
2378 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2380 //Make blacklisting persistent in the config file
2381 append_config_file(mesh, n->name, "blacklisted", "yes");
2383 //Immediately terminate any connections we have with the blacklisted node
2384 for list_each(connection_t, c, mesh->connections) {
2386 terminate_connection(mesh, c, c->status.active);
2390 pthread_mutex_unlock(&(mesh->mesh_mutex));
2393 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2394 if(!mesh || !node) {
2395 meshlink_errno = MESHLINK_EINVAL;
2399 pthread_mutex_lock(&(mesh->mesh_mutex));
2401 node_t *n = (node_t *)node;
2402 n->status.blacklisted = false;
2404 //TODO: remove blacklisted = yes from the config file
2406 pthread_mutex_unlock(&(mesh->mesh_mutex));
2410 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2411 mesh->default_blacklist = blacklist;
2414 /* Hint that a hostname may be found at an address
2415 * See header file for detailed comment.
2417 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2418 if(!mesh || !node || !addr) {
2422 // Ignore hints about ourself.
2423 if((node_t *)node == mesh->self) {
2427 pthread_mutex_lock(&(mesh->mesh_mutex));
2429 char *host = NULL, *port = NULL, *str = NULL;
2430 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2433 xasprintf(&str, "%s %s", host, port);
2435 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2436 modify_config_file(mesh, node->name, "Address", str, 5);
2438 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2446 pthread_mutex_unlock(&(mesh->mesh_mutex));
2447 // @TODO do we want to fire off a connection attempt right away?
2450 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2452 node_t *n = utcp->priv;
2453 meshlink_handle_t *mesh = n->mesh;
2454 return mesh->channel_accept_cb;
2457 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2458 meshlink_channel_t *channel = connection->priv;
2464 node_t *n = channel->node;
2465 meshlink_handle_t *mesh = n->mesh;
2467 if(n->status.destroyed) {
2468 meshlink_channel_close(mesh, channel);
2469 } else if(channel->receive_cb) {
2470 channel->receive_cb(mesh, channel, data, len);
2476 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2477 node_t *n = utcp_connection->utcp->priv;
2483 meshlink_handle_t *mesh = n->mesh;
2485 if(!mesh->channel_accept_cb) {
2489 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2491 channel->c = utcp_connection;
2493 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2494 utcp_accept(utcp_connection, channel_recv, channel);
2500 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2501 node_t *n = utcp->priv;
2503 if(n->status.destroyed) {
2507 meshlink_handle_t *mesh = n->mesh;
2508 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2511 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2512 if(!mesh || !channel) {
2513 meshlink_errno = MESHLINK_EINVAL;
2517 channel->receive_cb = cb;
2520 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2522 node_t *n = (node_t *)source;
2528 utcp_recv(n->utcp, data, len);
2531 static void channel_poll(struct utcp_connection *connection, size_t len) {
2532 meshlink_channel_t *channel = connection->priv;
2538 node_t *n = channel->node;
2539 meshlink_handle_t *mesh = n->mesh;
2541 if(channel->poll_cb) {
2542 channel->poll_cb(mesh, channel, len);
2546 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2548 channel->poll_cb = cb;
2549 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2552 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2554 meshlink_errno = MESHLINK_EINVAL;
2558 pthread_mutex_lock(&mesh->mesh_mutex);
2559 mesh->channel_accept_cb = cb;
2560 mesh->receive_cb = channel_receive;
2562 for splay_each(node_t, n, mesh->nodes) {
2563 if(!n->utcp && n != mesh->self) {
2564 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2568 pthread_mutex_unlock(&mesh->mesh_mutex);
2571 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) {
2573 abort(); // TODO: handle non-NULL data
2576 if(!mesh || !node) {
2577 meshlink_errno = MESHLINK_EINVAL;
2581 node_t *n = (node_t *)node;
2584 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2585 mesh->receive_cb = channel_receive;
2588 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2593 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2595 channel->receive_cb = cb;
2596 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2599 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2607 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) {
2608 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2611 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2612 if(!mesh || !channel) {
2613 meshlink_errno = MESHLINK_EINVAL;
2617 utcp_shutdown(channel->c, direction);
2620 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2621 if(!mesh || !channel) {
2622 meshlink_errno = MESHLINK_EINVAL;
2626 utcp_close(channel->c);
2630 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2631 if(!mesh || !channel) {
2632 meshlink_errno = MESHLINK_EINVAL;
2641 meshlink_errno = MESHLINK_EINVAL;
2645 // TODO: more finegrained locking.
2646 // Ideally we want to put the data into the UTCP connection's send buffer.
2647 // Then, preferrably only if there is room in the receiver window,
2648 // kick the meshlink thread to go send packets.
2650 pthread_mutex_lock(&mesh->mesh_mutex);
2651 ssize_t retval = utcp_send(channel->c, data, len);
2652 pthread_mutex_unlock(&mesh->mesh_mutex);
2655 meshlink_errno = MESHLINK_ENETWORK;
2661 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2662 if(!mesh || !channel) {
2663 meshlink_errno = MESHLINK_EINVAL;
2667 return channel->c->flags;
2670 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2671 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2672 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2675 if(mesh->node_status_cb) {
2676 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2680 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2681 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2685 n->status.duplicate = true;
2686 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2689 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2693 meshlink_errno = MESHLINK_EINVAL;
2697 pthread_mutex_lock(&mesh->mesh_mutex);
2699 if(mesh->discovery == enable) {
2703 if(mesh->threadstarted) {
2705 discovery_start(mesh);
2707 discovery_stop(mesh);
2711 mesh->discovery = enable;
2714 pthread_mutex_unlock(&mesh->mesh_mutex);
2718 meshlink_errno = MESHLINK_ENOTSUP;
2722 static void __attribute__((constructor)) meshlink_init(void) {
2725 randomize(&seed, sizeof(seed));
2729 static void __attribute__((destructor)) meshlink_exit(void) {
2733 /// Device class traits
2734 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2735 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2736 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2737 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2738 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN