2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014, 2017 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 bool finalize_join(meshlink_handle_t *mesh) {
538 char *name = xstrdup(get_value(mesh->data, "Name"));
541 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
545 if(!check_id(name)) {
546 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
550 char filename[PATH_MAX];
551 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
553 FILE *f = fopen(filename, "w");
556 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
560 fprintf(f, "Name = %s\n", name);
562 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
563 FILE *fh = fopen(filename, "w");
566 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
571 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
572 // Other chunks go unfiltered to their respective host config files
573 const char *p = mesh->data;
576 while((l = get_line(&p))) {
582 // Split line into variable and value
583 int len = strcspn(l, "\t =");
585 value += strspn(value, "\t ");
589 value += strspn(value, "\t ");
595 if(!strcasecmp(l, "Name"))
596 if(strcmp(value, name)) {
600 } else if(!strcasecmp(l, "NetName")) {
604 // Check the list of known variables
608 for(i = 0; variables[i].name; i++) {
609 if(strcasecmp(l, variables[i].name)) {
617 // Ignore unknown and unsafe variables
619 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
621 } else if(!(variables[i].type & VAR_SAFE)) {
622 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
626 // Copy the safe variable to the right config file
627 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
632 while(l && !strcasecmp(l, "Name")) {
633 if(!check_id(value)) {
634 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
638 if(!strcmp(value, name)) {
639 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
643 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
644 f = fopen(filename, "w");
647 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
651 while((l = get_line(&p))) {
652 if(!strcmp(l, "#---------------------------------------------------------------#")) {
656 int len = strcspn(l, "\t =");
658 if(len == 4 && !strncasecmp(l, "Name", 4)) {
660 value += strspn(value, "\t ");
664 value += strspn(value, "\t ");
678 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
685 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
686 fprintf(fh, "Port = %s\n", mesh->myport);
690 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
693 free(mesh->self->name);
694 free(mesh->self->connection->name);
695 mesh->self->name = xstrdup(name);
696 mesh->self->connection->name = name;
698 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
700 load_all_nodes(mesh);
705 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
707 meshlink_handle_t *mesh = handle;
708 const char *ptr = data;
711 int result = send(mesh->sock, ptr, len, 0);
713 if(result == -1 && errno == EINTR) {
715 } else if(result <= 0) {
726 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
727 meshlink_handle_t *mesh = handle;
730 case SPTPS_HANDSHAKE:
731 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
734 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
735 memcpy(mesh->data + mesh->thedatalen, msg, len);
736 mesh->thedatalen += len;
737 mesh->data[mesh->thedatalen] = 0;
741 mesh->thedatalen = 0;
742 return finalize_join(mesh);
745 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
746 shutdown(mesh->sock, SHUT_RDWR);
747 mesh->success = true;
757 static bool recvline(meshlink_handle_t *mesh, size_t len) {
758 char *newline = NULL;
764 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
765 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
767 if(result == -1 && errno == EINTR) {
769 } else if(result <= 0) {
773 mesh->blen += result;
776 if((size_t)(newline - mesh->buffer) >= len) {
780 len = newline - mesh->buffer;
782 memcpy(mesh->line, mesh->buffer, len);
784 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
785 mesh->blen -= len + 1;
789 static bool sendline(int fd, char *format, ...) {
790 static char buffer[4096];
795 va_start(ap, format);
796 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
799 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
807 int result = send(fd, p, blen, MSG_NOSIGNAL);
809 if(result == -1 && errno == EINTR) {
811 } else if(result <= 0) {
822 static const char *errstr[] = {
823 [MESHLINK_OK] = "No error",
824 [MESHLINK_EINVAL] = "Invalid argument",
825 [MESHLINK_ENOMEM] = "Out of memory",
826 [MESHLINK_ENOENT] = "No such node",
827 [MESHLINK_EEXIST] = "Node already exists",
828 [MESHLINK_EINTERNAL] = "Internal error",
829 [MESHLINK_ERESOLV] = "Could not resolve hostname",
830 [MESHLINK_ESTORAGE] = "Storage error",
831 [MESHLINK_ENETWORK] = "Network error",
832 [MESHLINK_EPEER] = "Error communicating with peer",
835 const char *meshlink_strerror(meshlink_errno_t err) {
836 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
837 return "Invalid error code";
843 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
846 char pubname[PATH_MAX], privname[PATH_MAX];
848 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
850 if(!(key = ecdsa_generate())) {
851 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
852 meshlink_errno = MESHLINK_EINTERNAL;
855 logger(mesh, MESHLINK_DEBUG, "Done.\n");
858 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
859 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
860 meshlink_errno = MESHLINK_ESTORAGE;
864 f = fopen(privname, "wb");
867 meshlink_errno = MESHLINK_ESTORAGE;
872 fchmod(fileno(f), 0600);
875 if(!ecdsa_write_pem_private_key(key, f)) {
876 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
879 meshlink_errno = MESHLINK_EINTERNAL;
885 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
886 f = fopen(pubname, "a");
889 meshlink_errno = MESHLINK_ESTORAGE;
893 char *pubkey = ecdsa_get_base64_public_key(key);
894 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
903 static struct timeval idle(event_loop_t *loop, void *data) {
905 meshlink_handle_t *mesh = data;
906 struct timeval t, tmin = {3600, 0};
908 for splay_each(node_t, n, mesh->nodes) {
913 t = utcp_timeout(n->utcp);
915 if(timercmp(&t, &tmin, <)) {
923 // Get our local address(es) by simulating connecting to an Internet host.
924 static void add_local_addresses(meshlink_handle_t *mesh) {
925 char host[NI_MAXHOST];
926 char entry[MAX_STRING_SIZE];
930 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
931 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
932 append_config_file(mesh, mesh->name, "Address", entry);
937 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
938 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
939 append_config_file(mesh, mesh->name, "Address", entry);
943 static bool meshlink_setup(meshlink_handle_t *mesh) {
944 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
945 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
946 meshlink_errno = MESHLINK_ESTORAGE;
950 char filename[PATH_MAX];
951 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
953 if(mkdir(filename, 0777) && errno != EEXIST) {
954 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
955 meshlink_errno = MESHLINK_ESTORAGE;
959 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
961 if(!access(filename, F_OK)) {
962 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
963 meshlink_errno = MESHLINK_EEXIST;
967 FILE *f = fopen(filename, "w");
970 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
971 meshlink_errno = MESHLINK_ESTORAGE;
975 fprintf(f, "Name = %s\n", mesh->name);
978 if(!ecdsa_keygen(mesh)) {
979 meshlink_errno = MESHLINK_EINTERNAL;
984 if(check_port(mesh) == 0) {
985 meshlink_errno = MESHLINK_ENETWORK;
993 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
994 // Validate arguments provided by the application
995 bool usingname = false;
997 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
999 if(!confbase || !*confbase) {
1000 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1001 meshlink_errno = MESHLINK_EINVAL;
1005 if(!appname || !*appname) {
1006 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1007 meshlink_errno = MESHLINK_EINVAL;
1011 if(!name || !*name) {
1012 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1014 } else { //check name only if there is a name != NULL
1016 if(!check_id(name)) {
1017 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1018 meshlink_errno = MESHLINK_EINVAL;
1025 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1026 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1027 meshlink_errno = MESHLINK_EINVAL;
1031 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1032 mesh->confbase = xstrdup(confbase);
1033 mesh->appname = xstrdup(appname);
1034 mesh->devclass = devclass;
1035 mesh->discovery = true;
1036 mesh->invitation_timeout = 604800; // 1 week
1039 mesh->name = xstrdup(name);
1043 pthread_mutexattr_t attr;
1044 pthread_mutexattr_init(&attr);
1045 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1046 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1048 mesh->threadstarted = false;
1049 event_loop_init(&mesh->loop);
1050 mesh->loop.data = mesh;
1052 meshlink_queue_init(&mesh->outpacketqueue);
1054 // Check whether meshlink.conf already exists
1056 char filename[PATH_MAX];
1057 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1059 if(access(filename, R_OK)) {
1060 if(errno == ENOENT) {
1061 // If not, create it
1062 if(!meshlink_setup(mesh)) {
1063 // meshlink_errno is set by meshlink_setup()
1067 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1068 meshlink_close(mesh);
1069 meshlink_errno = MESHLINK_ESTORAGE;
1074 // Read the configuration
1076 init_configuration(&mesh->config);
1078 if(!read_server_config(mesh)) {
1079 meshlink_close(mesh);
1080 meshlink_errno = MESHLINK_ESTORAGE;
1085 struct WSAData wsa_state;
1087 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1091 // Setup up everything
1092 // TODO: we should not open listening sockets yet
1094 if(!setup_network(mesh)) {
1095 meshlink_close(mesh);
1096 meshlink_errno = MESHLINK_ENETWORK;
1100 add_local_addresses(mesh);
1102 idle_set(&mesh->loop, idle, mesh);
1104 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1108 static void *meshlink_main_loop(void *arg) {
1109 meshlink_handle_t *mesh = arg;
1111 pthread_mutex_lock(&(mesh->mesh_mutex));
1113 try_outgoing_connections(mesh);
1115 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1117 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1119 pthread_mutex_unlock(&(mesh->mesh_mutex));
1123 bool meshlink_start(meshlink_handle_t *mesh) {
1125 meshlink_errno = MESHLINK_EINVAL;
1129 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1131 pthread_mutex_lock(&(mesh->mesh_mutex));
1133 if(mesh->threadstarted) {
1134 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1135 pthread_mutex_unlock(&(mesh->mesh_mutex));
1139 if(mesh->listen_socket[0].tcp.fd < 0) {
1140 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1141 meshlink_errno = MESHLINK_ENETWORK;
1145 mesh->thedatalen = 0;
1147 // TODO: open listening sockets first
1149 //Check that a valid name is set
1151 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1153 pthread_mutex_unlock(&(mesh->mesh_mutex));
1157 // Start the main thread
1159 event_loop_start(&mesh->loop);
1161 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1162 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1163 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1164 meshlink_errno = MESHLINK_EINTERNAL;
1165 event_loop_stop(&mesh->loop);
1166 pthread_mutex_unlock(&(mesh->mesh_mutex));
1170 mesh->threadstarted = true;
1172 if(mesh->discovery) {
1173 discovery_start(mesh);
1176 pthread_mutex_unlock(&(mesh->mesh_mutex));
1180 void meshlink_stop(meshlink_handle_t *mesh) {
1182 meshlink_errno = MESHLINK_EINVAL;
1186 pthread_mutex_lock(&(mesh->mesh_mutex));
1187 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1190 if(mesh->discovery) {
1191 discovery_stop(mesh);
1194 // Shut down the main thread
1195 event_loop_stop(&mesh->loop);
1197 // Send ourselves a UDP packet to kick the event loop
1198 for(int i = 0; i < mesh->listen_sockets; i++) {
1200 socklen_t salen = sizeof(sa.sa);
1202 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1203 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1207 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1208 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1212 if(mesh->threadstarted) {
1213 // Wait for the main thread to finish
1214 pthread_mutex_unlock(&(mesh->mesh_mutex));
1215 pthread_join(mesh->thread, NULL);
1216 pthread_mutex_lock(&(mesh->mesh_mutex));
1218 mesh->threadstarted = false;
1221 // Close all metaconnections
1222 if(mesh->connections) {
1223 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1225 connection_t *c = node->data;
1227 terminate_connection(mesh, c, false);
1231 if(mesh->outgoings) {
1232 list_delete_list(mesh->outgoings);
1233 mesh->outgoings = NULL;
1236 pthread_mutex_unlock(&(mesh->mesh_mutex));
1239 void meshlink_close(meshlink_handle_t *mesh) {
1240 if(!mesh || !mesh->confbase) {
1241 meshlink_errno = MESHLINK_EINVAL;
1245 // stop can be called even if mesh has not been started
1246 meshlink_stop(mesh);
1248 // lock is not released after this
1249 pthread_mutex_lock(&(mesh->mesh_mutex));
1251 // Close and free all resources used.
1253 close_network_connections(mesh);
1255 logger(mesh, MESHLINK_INFO, "Terminating");
1257 exit_configuration(&mesh->config);
1258 event_loop_exit(&mesh->loop);
1262 if(mesh->confbase) {
1268 ecdsa_free(mesh->invitation_key);
1271 free(mesh->appname);
1272 free(mesh->confbase);
1273 pthread_mutex_destroy(&(mesh->mesh_mutex));
1275 memset(mesh, 0, sizeof(*mesh));
1280 static void deltree(const char *dirname) {
1281 DIR *d = opendir(dirname);
1286 while((ent = readdir(d))) {
1287 if(ent->d_name[0] == '.') {
1291 char filename[PATH_MAX];
1292 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1294 if(unlink(filename)) {
1306 bool meshlink_destroy(const char *confbase) {
1308 meshlink_errno = MESHLINK_EINVAL;
1312 char filename[PATH_MAX];
1313 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1315 if(unlink(filename)) {
1316 if(errno == ENOENT) {
1317 meshlink_errno = MESHLINK_ENOENT;
1320 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1321 meshlink_errno = MESHLINK_ESTORAGE;
1331 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1333 meshlink_errno = MESHLINK_EINVAL;
1337 pthread_mutex_lock(&(mesh->mesh_mutex));
1338 mesh->receive_cb = cb;
1339 pthread_mutex_unlock(&(mesh->mesh_mutex));
1342 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1344 meshlink_errno = MESHLINK_EINVAL;
1348 pthread_mutex_lock(&(mesh->mesh_mutex));
1349 mesh->node_status_cb = cb;
1350 pthread_mutex_unlock(&(mesh->mesh_mutex));
1353 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1355 pthread_mutex_lock(&(mesh->mesh_mutex));
1357 mesh->log_level = cb ? level : 0;
1358 pthread_mutex_unlock(&(mesh->mesh_mutex));
1361 global_log_level = cb ? level : 0;
1365 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1366 meshlink_packethdr_t *hdr;
1368 // Validate arguments
1369 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1370 meshlink_errno = MESHLINK_EINVAL;
1379 meshlink_errno = MESHLINK_EINVAL;
1383 // Prepare the packet
1384 vpn_packet_t *packet = malloc(sizeof(*packet));
1387 meshlink_errno = MESHLINK_ENOMEM;
1391 packet->probe = false;
1392 packet->tcp = false;
1393 packet->len = len + sizeof(*hdr);
1395 hdr = (meshlink_packethdr_t *)packet->data;
1396 memset(hdr, 0, sizeof(*hdr));
1397 // leave the last byte as 0 to make sure strings are always
1398 // null-terminated if they are longer than the buffer
1399 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1400 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1402 memcpy(packet->data + sizeof(*hdr), data, len);
1405 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1407 meshlink_errno = MESHLINK_ENOMEM;
1411 // Notify event loop
1412 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1417 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1419 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1425 mesh->self->in_packets++;
1426 mesh->self->in_bytes += packet->len;
1427 route(mesh, mesh->self, packet);
1430 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1431 if(!mesh || !destination) {
1432 meshlink_errno = MESHLINK_EINVAL;
1436 pthread_mutex_lock(&(mesh->mesh_mutex));
1438 node_t *n = (node_t *)destination;
1440 if(!n->status.reachable) {
1441 pthread_mutex_unlock(&(mesh->mesh_mutex));
1444 } else if(n->mtuprobes > 30 && n->minmtu) {
1445 pthread_mutex_unlock(&(mesh->mesh_mutex));
1448 pthread_mutex_unlock(&(mesh->mesh_mutex));
1453 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1454 if(!mesh || !node) {
1455 meshlink_errno = MESHLINK_EINVAL;
1459 pthread_mutex_lock(&(mesh->mesh_mutex));
1461 node_t *n = (node_t *)node;
1463 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1464 meshlink_errno = MESHLINK_EINTERNAL;
1465 pthread_mutex_unlock(&(mesh->mesh_mutex));
1469 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1472 meshlink_errno = MESHLINK_EINTERNAL;
1475 pthread_mutex_unlock(&(mesh->mesh_mutex));
1479 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1481 meshlink_errno = MESHLINK_EINVAL;
1485 return (meshlink_node_t *)mesh->self;
1488 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1489 if(!mesh || !name) {
1490 meshlink_errno = MESHLINK_EINVAL;
1494 meshlink_node_t *node = NULL;
1496 pthread_mutex_lock(&(mesh->mesh_mutex));
1497 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1498 pthread_mutex_unlock(&(mesh->mesh_mutex));
1502 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1503 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1504 meshlink_errno = MESHLINK_EINVAL;
1508 meshlink_node_t **result;
1511 pthread_mutex_lock(&(mesh->mesh_mutex));
1513 *nmemb = mesh->nodes->count;
1514 result = realloc(nodes, *nmemb * sizeof(*nodes));
1517 meshlink_node_t **p = result;
1519 for splay_each(node_t, n, mesh->nodes) {
1520 *p++ = (meshlink_node_t *)n;
1525 meshlink_errno = MESHLINK_ENOMEM;
1528 pthread_mutex_unlock(&(mesh->mesh_mutex));
1533 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1534 if(!mesh || !data || !len || !signature || !siglen) {
1535 meshlink_errno = MESHLINK_EINVAL;
1539 if(*siglen < MESHLINK_SIGLEN) {
1540 meshlink_errno = MESHLINK_EINVAL;
1544 pthread_mutex_lock(&(mesh->mesh_mutex));
1546 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1547 meshlink_errno = MESHLINK_EINTERNAL;
1548 pthread_mutex_unlock(&(mesh->mesh_mutex));
1552 *siglen = MESHLINK_SIGLEN;
1553 pthread_mutex_unlock(&(mesh->mesh_mutex));
1557 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1558 if(!mesh || !data || !len || !signature) {
1559 meshlink_errno = MESHLINK_EINVAL;
1563 if(siglen != MESHLINK_SIGLEN) {
1564 meshlink_errno = MESHLINK_EINVAL;
1568 pthread_mutex_lock(&(mesh->mesh_mutex));
1572 struct node_t *n = (struct node_t *)source;
1573 node_read_ecdsa_public_key(mesh, n);
1576 meshlink_errno = MESHLINK_EINTERNAL;
1579 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1582 pthread_mutex_unlock(&(mesh->mesh_mutex));
1586 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1587 char filename[PATH_MAX];
1589 pthread_mutex_lock(&(mesh->mesh_mutex));
1591 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1593 if(mkdir(filename, 0700) && errno != EEXIST) {
1594 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1595 meshlink_errno = MESHLINK_ESTORAGE;
1596 pthread_mutex_unlock(&(mesh->mesh_mutex));
1600 // Count the number of valid invitations, clean up old ones
1601 DIR *dir = opendir(filename);
1604 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1605 meshlink_errno = MESHLINK_ESTORAGE;
1606 pthread_mutex_unlock(&(mesh->mesh_mutex));
1613 time_t deadline = time(NULL) - 604800; // 1 week in the past
1615 while((ent = readdir(dir))) {
1616 if(strlen(ent->d_name) != 24) {
1620 char invname[PATH_MAX];
1623 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1624 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1628 if(!stat(invname, &st)) {
1629 if(mesh->invitation_key && deadline < st.st_mtime) {
1635 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1641 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1643 meshlink_errno = MESHLINK_ESTORAGE;
1644 pthread_mutex_unlock(&(mesh->mesh_mutex));
1650 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1652 // Remove the key if there are no outstanding invitations.
1656 if(mesh->invitation_key) {
1657 ecdsa_free(mesh->invitation_key);
1658 mesh->invitation_key = NULL;
1662 if(mesh->invitation_key) {
1663 pthread_mutex_unlock(&(mesh->mesh_mutex));
1667 // Create a new key if necessary.
1668 FILE *f = fopen(filename, "rb");
1671 if(errno != ENOENT) {
1672 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1673 meshlink_errno = MESHLINK_ESTORAGE;
1674 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678 mesh->invitation_key = ecdsa_generate();
1680 if(!mesh->invitation_key) {
1681 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1682 meshlink_errno = MESHLINK_EINTERNAL;
1683 pthread_mutex_unlock(&(mesh->mesh_mutex));
1687 f = fopen(filename, "wb");
1690 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1691 meshlink_errno = MESHLINK_ESTORAGE;
1692 pthread_mutex_unlock(&(mesh->mesh_mutex));
1696 chmod(filename, 0600);
1697 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1700 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1703 if(!mesh->invitation_key) {
1704 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1705 meshlink_errno = MESHLINK_ESTORAGE;
1709 pthread_mutex_unlock(&(mesh->mesh_mutex));
1710 return mesh->invitation_key;
1713 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1714 if(!mesh || !node || !address) {
1715 meshlink_errno = MESHLINK_EINVAL;
1719 if(!is_valid_hostname(address)) {
1720 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1721 meshlink_errno = MESHLINK_EINVAL;
1725 if(port && !is_valid_port(port)) {
1726 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1727 meshlink_errno = MESHLINK_EINVAL;
1731 char *canonical_address;
1734 xasprintf(&canonical_address, "%s %s", address, port);
1736 canonical_address = xstrdup(address);
1739 pthread_mutex_lock(&(mesh->mesh_mutex));
1740 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1741 pthread_mutex_unlock(&(mesh->mesh_mutex));
1743 free(canonical_address);
1747 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1748 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1751 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1753 meshlink_errno = MESHLINK_EINVAL;
1757 char *address = meshlink_get_external_address(mesh);
1765 pthread_mutex_lock(&(mesh->mesh_mutex));
1766 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1767 pthread_mutex_unlock(&(mesh->mesh_mutex));
1773 int meshlink_get_port(meshlink_handle_t *mesh) {
1775 meshlink_errno = MESHLINK_EINVAL;
1780 meshlink_errno = MESHLINK_EINTERNAL;
1784 return atoi(mesh->myport);
1787 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1788 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1789 meshlink_errno = MESHLINK_EINVAL;
1793 if(mesh->myport && port == atoi(mesh->myport)) {
1797 if(!try_bind(port)) {
1798 meshlink_errno = MESHLINK_ENETWORK;
1804 pthread_mutex_lock(&(mesh->mesh_mutex));
1806 if(mesh->threadstarted) {
1807 meshlink_errno = MESHLINK_EINVAL;
1811 close_network_connections(mesh);
1812 exit_configuration(&mesh->config);
1815 snprintf(portstr, sizeof(portstr), "%d", port);
1816 portstr[sizeof(portstr) - 1] = 0;
1818 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1820 init_configuration(&mesh->config);
1822 if(!read_server_config(mesh)) {
1823 meshlink_errno = MESHLINK_ESTORAGE;
1824 } else if(!setup_network(mesh)) {
1825 meshlink_errno = MESHLINK_ENETWORK;
1831 pthread_mutex_unlock(&(mesh->mesh_mutex));
1836 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1837 mesh->invitation_timeout = timeout;
1840 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1842 meshlink_errno = MESHLINK_EINVAL;
1846 pthread_mutex_lock(&(mesh->mesh_mutex));
1848 // Check validity of the new node's name
1849 if(!check_id(name)) {
1850 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1851 meshlink_errno = MESHLINK_EINVAL;
1852 pthread_mutex_unlock(&(mesh->mesh_mutex));
1856 // Ensure no host configuration file with that name exists
1857 char filename[PATH_MAX];
1858 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1860 if(!access(filename, F_OK)) {
1861 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1862 meshlink_errno = MESHLINK_EEXIST;
1863 pthread_mutex_unlock(&(mesh->mesh_mutex));
1867 // Ensure no other nodes know about this name
1868 if(meshlink_get_node(mesh, name)) {
1869 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1870 meshlink_errno = MESHLINK_EEXIST;
1871 pthread_mutex_unlock(&(mesh->mesh_mutex));
1875 // Get the local address
1876 char *address = get_my_hostname(mesh);
1879 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1880 meshlink_errno = MESHLINK_ERESOLV;
1881 pthread_mutex_unlock(&(mesh->mesh_mutex));
1885 if(!refresh_invitation_key(mesh)) {
1886 meshlink_errno = MESHLINK_EINTERNAL;
1887 pthread_mutex_unlock(&(mesh->mesh_mutex));
1893 // Create a hash of the key.
1894 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1895 sha512(fingerprint, strlen(fingerprint), hash);
1896 b64encode_urlsafe(hash, hash, 18);
1898 // Create a random cookie for this invitation.
1900 randomize(cookie, 18);
1902 // Create a filename that doesn't reveal the cookie itself
1903 char buf[18 + strlen(fingerprint)];
1904 char cookiehash[64];
1905 memcpy(buf, cookie, 18);
1906 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1907 sha512(buf, sizeof(buf), cookiehash);
1908 b64encode_urlsafe(cookiehash, cookiehash, 18);
1910 b64encode_urlsafe(cookie, cookie, 18);
1914 // Create a file containing the details of the invitation.
1915 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1916 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1919 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1920 meshlink_errno = MESHLINK_ESTORAGE;
1921 pthread_mutex_unlock(&(mesh->mesh_mutex));
1925 FILE *f = fdopen(ifd, "w");
1931 // Fill in the details.
1932 fprintf(f, "Name = %s\n", name);
1933 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1935 // Copy Broadcast and Mode
1936 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1937 FILE *tc = fopen(filename, "r");
1942 while(fgets(buf, sizeof(buf), tc)) {
1943 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1944 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1947 // Make sure there is a newline character.
1948 if(!strchr(buf, '\n')) {
1956 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1957 meshlink_errno = MESHLINK_ESTORAGE;
1958 pthread_mutex_unlock(&(mesh->mesh_mutex));
1962 fprintf(f, "#---------------------------------------------------------------#\n");
1963 fprintf(f, "Name = %s\n", mesh->self->name);
1965 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1969 // Create an URL from the local address, key hash and cookie
1971 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1974 pthread_mutex_unlock(&(mesh->mesh_mutex));
1978 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1979 if(!mesh || !invitation) {
1980 meshlink_errno = MESHLINK_EINVAL;
1984 pthread_mutex_lock(&(mesh->mesh_mutex));
1986 //Before doing meshlink_join make sure we are not connected to another mesh
1987 if(mesh->threadstarted) {
1988 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1989 meshlink_errno = MESHLINK_EINVAL;
1990 pthread_mutex_unlock(&(mesh->mesh_mutex));
1994 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1995 char copy[strlen(invitation) + 1];
1996 strcpy(copy, invitation);
1998 // Split the invitation URL into hostname, port, key hash and cookie.
2000 char *slash = strchr(copy, '/');
2008 if(strlen(slash) != 48) {
2012 char *address = copy;
2013 char *port = strrchr(address, ':');
2021 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2025 // Generate a throw-away key for the invitation.
2026 ecdsa_t *key = ecdsa_generate();
2029 meshlink_errno = MESHLINK_EINTERNAL;
2030 pthread_mutex_unlock(&(mesh->mesh_mutex));
2034 char *b64key = ecdsa_get_base64_public_key(key);
2038 while(address && *address) {
2039 // We allow commas in the address part to support multiple addresses in one invitation URL.
2040 comma = strchr(address, ',');
2046 // IPv6 address are enclosed in brackets, per RFC 3986
2047 if(*address == '[') {
2049 char *bracket = strchr(address, ']');
2057 if(comma && bracket != comma) {
2062 // Connect to the meshlink daemon mentioned in the URL.
2063 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2066 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2067 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2069 if(mesh->sock == -1) {
2070 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2071 meshlink_errno = MESHLINK_ENETWORK;
2075 set_timeout(mesh->sock, 5000);
2077 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2078 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2079 meshlink_errno = MESHLINK_ENETWORK;
2080 closesocket(mesh->sock);
2088 meshlink_errno = MESHLINK_ERESOLV;
2091 if(mesh->sock != -1 || !comma) {
2098 if(mesh->sock == -1) {
2099 pthread_mutex_unlock(&mesh->mesh_mutex);
2103 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2105 // Tell him we have an invitation, and give him our throw-away key.
2109 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2110 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2111 closesocket(mesh->sock);
2112 meshlink_errno = MESHLINK_ENETWORK;
2113 pthread_mutex_unlock(&(mesh->mesh_mutex));
2119 char hisname[4096] = "";
2120 int code, hismajor, hisminor = 0;
2122 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) {
2123 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2124 closesocket(mesh->sock);
2125 meshlink_errno = MESHLINK_ENETWORK;
2126 pthread_mutex_unlock(&(mesh->mesh_mutex));
2130 // Check if the hash of the key he gave us matches the hash in the URL.
2131 char *fingerprint = mesh->line + 2;
2134 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2135 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2136 meshlink_errno = MESHLINK_EINTERNAL;
2137 pthread_mutex_unlock(&(mesh->mesh_mutex));
2141 if(memcmp(hishash, mesh->hash, 18)) {
2142 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2143 meshlink_errno = MESHLINK_EPEER;
2144 pthread_mutex_unlock(&(mesh->mesh_mutex));
2149 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2152 meshlink_errno = MESHLINK_EINTERNAL;
2153 pthread_mutex_unlock(&(mesh->mesh_mutex));
2157 // Start an SPTPS session
2158 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2159 meshlink_errno = MESHLINK_EINTERNAL;
2160 pthread_mutex_unlock(&(mesh->mesh_mutex));
2164 // Feed rest of input buffer to SPTPS
2165 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2166 meshlink_errno = MESHLINK_EPEER;
2167 pthread_mutex_unlock(&(mesh->mesh_mutex));
2173 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2175 if(errno == EINTR) {
2179 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2180 meshlink_errno = MESHLINK_ENETWORK;
2181 pthread_mutex_unlock(&(mesh->mesh_mutex));
2185 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2186 meshlink_errno = MESHLINK_EPEER;
2187 pthread_mutex_unlock(&(mesh->mesh_mutex));
2192 sptps_stop(&mesh->sptps);
2195 closesocket(mesh->sock);
2197 if(!mesh->success) {
2198 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2199 meshlink_errno = MESHLINK_EPEER;
2200 pthread_mutex_unlock(&(mesh->mesh_mutex));
2204 pthread_mutex_unlock(&(mesh->mesh_mutex));
2208 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2209 meshlink_errno = MESHLINK_EINVAL;
2210 pthread_mutex_unlock(&(mesh->mesh_mutex));
2214 char *meshlink_export(meshlink_handle_t *mesh) {
2216 meshlink_errno = MESHLINK_EINVAL;
2220 pthread_mutex_lock(&(mesh->mesh_mutex));
2222 char filename[PATH_MAX];
2223 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2224 FILE *f = fopen(filename, "r");
2227 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2228 meshlink_errno = MESHLINK_ESTORAGE;
2229 pthread_mutex_unlock(&(mesh->mesh_mutex));
2233 fseek(f, 0, SEEK_END);
2234 int fsize = ftell(f);
2237 size_t len = fsize + 9 + strlen(mesh->self->name);
2238 char *buf = xmalloc(len);
2239 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2241 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2242 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2245 meshlink_errno = MESHLINK_ESTORAGE;
2246 pthread_mutex_unlock(&(mesh->mesh_mutex));
2253 pthread_mutex_unlock(&(mesh->mesh_mutex));
2257 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2258 if(!mesh || !data) {
2259 meshlink_errno = MESHLINK_EINVAL;
2263 pthread_mutex_lock(&(mesh->mesh_mutex));
2265 if(strncmp(data, "Name = ", 7)) {
2266 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2267 meshlink_errno = MESHLINK_EPEER;
2268 pthread_mutex_unlock(&(mesh->mesh_mutex));
2272 char *end = strchr(data + 7, '\n');
2275 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2276 meshlink_errno = MESHLINK_EPEER;
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2281 int len = end - (data + 7);
2283 memcpy(name, data + 7, len);
2286 if(!check_id(name)) {
2287 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2288 meshlink_errno = MESHLINK_EPEER;
2289 pthread_mutex_unlock(&(mesh->mesh_mutex));
2293 char filename[PATH_MAX];
2294 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2296 if(!access(filename, F_OK)) {
2297 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2298 meshlink_errno = MESHLINK_EEXIST;
2299 pthread_mutex_unlock(&(mesh->mesh_mutex));
2303 if(errno != ENOENT) {
2304 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2305 meshlink_errno = MESHLINK_ESTORAGE;
2306 pthread_mutex_unlock(&(mesh->mesh_mutex));
2310 FILE *f = fopen(filename, "w");
2313 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2314 meshlink_errno = MESHLINK_ESTORAGE;
2315 pthread_mutex_unlock(&(mesh->mesh_mutex));
2319 fwrite(end + 1, strlen(end + 1), 1, f);
2322 load_all_nodes(mesh);
2324 pthread_mutex_unlock(&(mesh->mesh_mutex));
2328 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2329 if(!mesh || !node) {
2330 meshlink_errno = MESHLINK_EINVAL;
2334 pthread_mutex_lock(&(mesh->mesh_mutex));
2338 n->status.blacklisted = true;
2339 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2341 //Make blacklisting persistent in the config file
2342 append_config_file(mesh, n->name, "blacklisted", "yes");
2344 pthread_mutex_unlock(&(mesh->mesh_mutex));
2348 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2349 if(!mesh || !node) {
2350 meshlink_errno = MESHLINK_EINVAL;
2354 pthread_mutex_lock(&(mesh->mesh_mutex));
2356 node_t *n = (node_t *)node;
2357 n->status.blacklisted = false;
2359 //TODO: remove blacklisted = yes from the config file
2361 pthread_mutex_unlock(&(mesh->mesh_mutex));
2365 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2366 mesh->default_blacklist = blacklist;
2369 /* Hint that a hostname may be found at an address
2370 * See header file for detailed comment.
2372 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2373 if(!mesh || !node || !addr) {
2377 // Ignore hints about ourself.
2378 if((node_t *)node == mesh->self) {
2382 pthread_mutex_lock(&(mesh->mesh_mutex));
2384 char *host = NULL, *port = NULL, *str = NULL;
2385 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2388 xasprintf(&str, "%s %s", host, port);
2390 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2391 modify_config_file(mesh, node->name, "Address", str, 5);
2393 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2401 pthread_mutex_unlock(&(mesh->mesh_mutex));
2402 // @TODO do we want to fire off a connection attempt right away?
2405 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2407 node_t *n = utcp->priv;
2408 meshlink_handle_t *mesh = n->mesh;
2409 return mesh->channel_accept_cb;
2412 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2413 meshlink_channel_t *channel = connection->priv;
2419 node_t *n = channel->node;
2420 meshlink_handle_t *mesh = n->mesh;
2422 if(n->status.destroyed) {
2423 meshlink_channel_close(mesh, channel);
2424 } else if(channel->receive_cb) {
2425 channel->receive_cb(mesh, channel, data, len);
2431 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2432 node_t *n = utcp_connection->utcp->priv;
2438 meshlink_handle_t *mesh = n->mesh;
2440 if(!mesh->channel_accept_cb) {
2444 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2446 channel->c = utcp_connection;
2448 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2449 utcp_accept(utcp_connection, channel_recv, channel);
2455 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2456 node_t *n = utcp->priv;
2458 if(n->status.destroyed) {
2462 meshlink_handle_t *mesh = n->mesh;
2463 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2466 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2467 if(!mesh || !channel) {
2468 meshlink_errno = MESHLINK_EINVAL;
2472 channel->receive_cb = cb;
2475 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2477 node_t *n = (node_t *)source;
2483 utcp_recv(n->utcp, data, len);
2486 static void channel_poll(struct utcp_connection *connection, size_t len) {
2487 meshlink_channel_t *channel = connection->priv;
2493 node_t *n = channel->node;
2494 meshlink_handle_t *mesh = n->mesh;
2496 if(channel->poll_cb) {
2497 channel->poll_cb(mesh, channel, len);
2501 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2503 channel->poll_cb = cb;
2504 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2507 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2509 meshlink_errno = MESHLINK_EINVAL;
2513 pthread_mutex_lock(&mesh->mesh_mutex);
2514 mesh->channel_accept_cb = cb;
2515 mesh->receive_cb = channel_receive;
2517 for splay_each(node_t, n, mesh->nodes) {
2518 if(!n->utcp && n != mesh->self) {
2519 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2523 pthread_mutex_unlock(&mesh->mesh_mutex);
2526 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) {
2528 abort(); // TODO: handle non-NULL data
2531 if(!mesh || !node) {
2532 meshlink_errno = MESHLINK_EINVAL;
2536 node_t *n = (node_t *)node;
2539 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2540 mesh->receive_cb = channel_receive;
2543 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2548 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2550 channel->receive_cb = cb;
2551 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2554 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2562 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) {
2563 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2566 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2567 if(!mesh || !channel) {
2568 meshlink_errno = MESHLINK_EINVAL;
2572 utcp_shutdown(channel->c, direction);
2575 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2576 if(!mesh || !channel) {
2577 meshlink_errno = MESHLINK_EINVAL;
2581 utcp_close(channel->c);
2585 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2586 if(!mesh || !channel) {
2587 meshlink_errno = MESHLINK_EINVAL;
2596 meshlink_errno = MESHLINK_EINVAL;
2600 // TODO: more finegrained locking.
2601 // Ideally we want to put the data into the UTCP connection's send buffer.
2602 // Then, preferrably only if there is room in the receiver window,
2603 // kick the meshlink thread to go send packets.
2605 pthread_mutex_lock(&mesh->mesh_mutex);
2606 ssize_t retval = utcp_send(channel->c, data, len);
2607 pthread_mutex_unlock(&mesh->mesh_mutex);
2610 meshlink_errno = MESHLINK_ENETWORK;
2616 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2617 if(!mesh || !channel) {
2618 meshlink_errno = MESHLINK_EINVAL;
2622 return channel->c->flags;
2625 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2626 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2627 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2630 if(mesh->node_status_cb) {
2631 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2635 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2637 meshlink_errno = MESHLINK_EINVAL;
2641 pthread_mutex_lock(&mesh->mesh_mutex);
2643 if(mesh->discovery == enable) {
2647 if(mesh->threadstarted) {
2649 discovery_start(mesh);
2651 discovery_stop(mesh);
2655 mesh->discovery = enable;
2658 pthread_mutex_unlock(&mesh->mesh_mutex);
2661 static void __attribute__((constructor)) meshlink_init(void) {
2664 randomize(&seed, sizeof(seed));
2668 static void __attribute__((destructor)) meshlink_exit(void) {
2672 /// Device class traits
2673 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2674 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2675 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2676 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2677 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN