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;
1038 mesh->name = xstrdup(name);
1042 pthread_mutexattr_t attr;
1043 pthread_mutexattr_init(&attr);
1044 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1045 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1047 mesh->threadstarted = false;
1048 event_loop_init(&mesh->loop);
1049 mesh->loop.data = mesh;
1051 meshlink_queue_init(&mesh->outpacketqueue);
1053 // Check whether meshlink.conf already exists
1055 char filename[PATH_MAX];
1056 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1058 if(access(filename, R_OK)) {
1059 if(errno == ENOENT) {
1060 // If not, create it
1061 if(!meshlink_setup(mesh)) {
1062 // meshlink_errno is set by meshlink_setup()
1066 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1067 meshlink_close(mesh);
1068 meshlink_errno = MESHLINK_ESTORAGE;
1073 // Read the configuration
1075 init_configuration(&mesh->config);
1077 if(!read_server_config(mesh)) {
1078 meshlink_close(mesh);
1079 meshlink_errno = MESHLINK_ESTORAGE;
1084 struct WSAData wsa_state;
1086 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1090 // Setup up everything
1091 // TODO: we should not open listening sockets yet
1093 if(!setup_network(mesh)) {
1094 meshlink_close(mesh);
1095 meshlink_errno = MESHLINK_ENETWORK;
1099 add_local_addresses(mesh);
1101 idle_set(&mesh->loop, idle, mesh);
1103 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1107 static void *meshlink_main_loop(void *arg) {
1108 meshlink_handle_t *mesh = arg;
1110 pthread_mutex_lock(&(mesh->mesh_mutex));
1112 try_outgoing_connections(mesh);
1114 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1116 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1118 pthread_mutex_unlock(&(mesh->mesh_mutex));
1122 bool meshlink_start(meshlink_handle_t *mesh) {
1124 meshlink_errno = MESHLINK_EINVAL;
1128 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1130 pthread_mutex_lock(&(mesh->mesh_mutex));
1132 if(mesh->threadstarted) {
1133 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1134 pthread_mutex_unlock(&(mesh->mesh_mutex));
1138 if(mesh->listen_socket[0].tcp.fd < 0) {
1139 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1140 meshlink_errno = MESHLINK_ENETWORK;
1144 mesh->thedatalen = 0;
1146 // TODO: open listening sockets first
1148 //Check that a valid name is set
1150 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1151 meshlink_errno = MESHLINK_EINVAL;
1152 pthread_mutex_unlock(&(mesh->mesh_mutex));
1156 // Start the main thread
1158 event_loop_start(&mesh->loop);
1160 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1161 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1162 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1163 meshlink_errno = MESHLINK_EINTERNAL;
1164 event_loop_stop(&mesh->loop);
1165 pthread_mutex_unlock(&(mesh->mesh_mutex));
1169 mesh->threadstarted = true;
1171 if(mesh->discovery) {
1172 discovery_start(mesh);
1175 pthread_mutex_unlock(&(mesh->mesh_mutex));
1179 void meshlink_stop(meshlink_handle_t *mesh) {
1181 meshlink_errno = MESHLINK_EINVAL;
1185 pthread_mutex_lock(&(mesh->mesh_mutex));
1186 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1189 if(mesh->discovery) {
1190 discovery_stop(mesh);
1193 // Shut down the main thread
1194 event_loop_stop(&mesh->loop);
1196 // Send ourselves a UDP packet to kick the event loop
1197 for(int i = 0; i < mesh->listen_sockets; i++) {
1199 socklen_t salen = sizeof(sa.sa);
1201 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1202 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1206 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1207 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1211 if(mesh->threadstarted) {
1212 // Wait for the main thread to finish
1213 pthread_mutex_unlock(&(mesh->mesh_mutex));
1214 pthread_join(mesh->thread, NULL);
1215 pthread_mutex_lock(&(mesh->mesh_mutex));
1217 mesh->threadstarted = false;
1220 // Close all metaconnections
1221 if(mesh->connections) {
1222 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1224 connection_t *c = node->data;
1226 terminate_connection(mesh, c, false);
1230 if(mesh->outgoings) {
1231 list_delete_list(mesh->outgoings);
1232 mesh->outgoings = NULL;
1235 pthread_mutex_unlock(&(mesh->mesh_mutex));
1238 void meshlink_close(meshlink_handle_t *mesh) {
1239 if(!mesh || !mesh->confbase) {
1240 meshlink_errno = MESHLINK_EINVAL;
1244 // stop can be called even if mesh has not been started
1245 meshlink_stop(mesh);
1247 // lock is not released after this
1248 pthread_mutex_lock(&(mesh->mesh_mutex));
1250 // Close and free all resources used.
1252 close_network_connections(mesh);
1254 logger(mesh, MESHLINK_INFO, "Terminating");
1256 exit_configuration(&mesh->config);
1257 event_loop_exit(&mesh->loop);
1261 if(mesh->confbase) {
1267 ecdsa_free(mesh->invitation_key);
1270 free(mesh->appname);
1271 free(mesh->confbase);
1272 pthread_mutex_destroy(&(mesh->mesh_mutex));
1274 memset(mesh, 0, sizeof(*mesh));
1279 static void deltree(const char *dirname) {
1280 DIR *d = opendir(dirname);
1285 while((ent = readdir(d))) {
1286 if(ent->d_name[0] == '.') {
1290 char filename[PATH_MAX];
1291 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1293 if(unlink(filename)) {
1305 bool meshlink_destroy(const char *confbase) {
1307 meshlink_errno = MESHLINK_EINVAL;
1311 char filename[PATH_MAX];
1312 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1314 if(unlink(filename)) {
1315 if(errno == ENOENT) {
1316 meshlink_errno = MESHLINK_ENOENT;
1319 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1320 meshlink_errno = MESHLINK_ESTORAGE;
1330 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1332 meshlink_errno = MESHLINK_EINVAL;
1336 pthread_mutex_lock(&(mesh->mesh_mutex));
1337 mesh->receive_cb = cb;
1338 pthread_mutex_unlock(&(mesh->mesh_mutex));
1341 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1343 meshlink_errno = MESHLINK_EINVAL;
1347 pthread_mutex_lock(&(mesh->mesh_mutex));
1348 mesh->node_status_cb = cb;
1349 pthread_mutex_unlock(&(mesh->mesh_mutex));
1352 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1354 pthread_mutex_lock(&(mesh->mesh_mutex));
1356 mesh->log_level = cb ? level : 0;
1357 pthread_mutex_unlock(&(mesh->mesh_mutex));
1360 global_log_level = cb ? level : 0;
1364 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1365 meshlink_packethdr_t *hdr;
1367 // Validate arguments
1368 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1369 meshlink_errno = MESHLINK_EINVAL;
1378 meshlink_errno = MESHLINK_EINVAL;
1382 // Prepare the packet
1383 vpn_packet_t *packet = malloc(sizeof(*packet));
1386 meshlink_errno = MESHLINK_ENOMEM;
1390 packet->probe = false;
1391 packet->tcp = false;
1392 packet->len = len + sizeof(*hdr);
1394 hdr = (meshlink_packethdr_t *)packet->data;
1395 memset(hdr, 0, sizeof(*hdr));
1396 // leave the last byte as 0 to make sure strings are always
1397 // null-terminated if they are longer than the buffer
1398 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1399 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1401 memcpy(packet->data + sizeof(*hdr), data, len);
1404 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1406 meshlink_errno = MESHLINK_ENOMEM;
1410 // Notify event loop
1411 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1416 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1418 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1424 mesh->self->in_packets++;
1425 mesh->self->in_bytes += packet->len;
1426 route(mesh, mesh->self, packet);
1429 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1430 if(!mesh || !destination) {
1431 meshlink_errno = MESHLINK_EINVAL;
1435 pthread_mutex_lock(&(mesh->mesh_mutex));
1437 node_t *n = (node_t *)destination;
1439 if(!n->status.reachable) {
1440 pthread_mutex_unlock(&(mesh->mesh_mutex));
1443 } else if(n->mtuprobes > 30 && n->minmtu) {
1444 pthread_mutex_unlock(&(mesh->mesh_mutex));
1447 pthread_mutex_unlock(&(mesh->mesh_mutex));
1452 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1453 if(!mesh || !node) {
1454 meshlink_errno = MESHLINK_EINVAL;
1458 pthread_mutex_lock(&(mesh->mesh_mutex));
1460 node_t *n = (node_t *)node;
1462 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1463 meshlink_errno = MESHLINK_EINTERNAL;
1464 pthread_mutex_unlock(&(mesh->mesh_mutex));
1468 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1471 meshlink_errno = MESHLINK_EINTERNAL;
1474 pthread_mutex_unlock(&(mesh->mesh_mutex));
1478 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1480 meshlink_errno = MESHLINK_EINVAL;
1484 return (meshlink_node_t *)mesh->self;
1487 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1488 if(!mesh || !name) {
1489 meshlink_errno = MESHLINK_EINVAL;
1493 meshlink_node_t *node = NULL;
1495 pthread_mutex_lock(&(mesh->mesh_mutex));
1496 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1497 pthread_mutex_unlock(&(mesh->mesh_mutex));
1501 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1502 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1503 meshlink_errno = MESHLINK_EINVAL;
1507 meshlink_node_t **result;
1510 pthread_mutex_lock(&(mesh->mesh_mutex));
1512 *nmemb = mesh->nodes->count;
1513 result = realloc(nodes, *nmemb * sizeof(*nodes));
1516 meshlink_node_t **p = result;
1518 for splay_each(node_t, n, mesh->nodes) {
1519 *p++ = (meshlink_node_t *)n;
1524 meshlink_errno = MESHLINK_ENOMEM;
1527 pthread_mutex_unlock(&(mesh->mesh_mutex));
1532 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1533 if(!mesh || !data || !len || !signature || !siglen) {
1534 meshlink_errno = MESHLINK_EINVAL;
1538 if(*siglen < MESHLINK_SIGLEN) {
1539 meshlink_errno = MESHLINK_EINVAL;
1543 pthread_mutex_lock(&(mesh->mesh_mutex));
1545 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1546 meshlink_errno = MESHLINK_EINTERNAL;
1547 pthread_mutex_unlock(&(mesh->mesh_mutex));
1551 *siglen = MESHLINK_SIGLEN;
1552 pthread_mutex_unlock(&(mesh->mesh_mutex));
1556 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1557 if(!mesh || !data || !len || !signature) {
1558 meshlink_errno = MESHLINK_EINVAL;
1562 if(siglen != MESHLINK_SIGLEN) {
1563 meshlink_errno = MESHLINK_EINVAL;
1567 pthread_mutex_lock(&(mesh->mesh_mutex));
1571 struct node_t *n = (struct node_t *)source;
1572 node_read_ecdsa_public_key(mesh, n);
1575 meshlink_errno = MESHLINK_EINTERNAL;
1578 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1581 pthread_mutex_unlock(&(mesh->mesh_mutex));
1585 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1586 char filename[PATH_MAX];
1588 pthread_mutex_lock(&(mesh->mesh_mutex));
1590 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1592 if(mkdir(filename, 0700) && errno != EEXIST) {
1593 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1594 meshlink_errno = MESHLINK_ESTORAGE;
1595 pthread_mutex_unlock(&(mesh->mesh_mutex));
1599 // Count the number of valid invitations, clean up old ones
1600 DIR *dir = opendir(filename);
1603 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1604 meshlink_errno = MESHLINK_ESTORAGE;
1605 pthread_mutex_unlock(&(mesh->mesh_mutex));
1612 time_t deadline = time(NULL) - 604800; // 1 week in the past
1614 while((ent = readdir(dir))) {
1615 if(strlen(ent->d_name) != 24) {
1619 char invname[PATH_MAX];
1622 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1623 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1627 if(!stat(invname, &st)) {
1628 if(mesh->invitation_key && deadline < st.st_mtime) {
1634 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1640 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1642 meshlink_errno = MESHLINK_ESTORAGE;
1643 pthread_mutex_unlock(&(mesh->mesh_mutex));
1649 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1651 // Remove the key if there are no outstanding invitations.
1655 if(mesh->invitation_key) {
1656 ecdsa_free(mesh->invitation_key);
1657 mesh->invitation_key = NULL;
1661 if(mesh->invitation_key) {
1662 pthread_mutex_unlock(&(mesh->mesh_mutex));
1666 // Create a new key if necessary.
1667 FILE *f = fopen(filename, "rb");
1670 if(errno != ENOENT) {
1671 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1672 meshlink_errno = MESHLINK_ESTORAGE;
1673 pthread_mutex_unlock(&(mesh->mesh_mutex));
1677 mesh->invitation_key = ecdsa_generate();
1679 if(!mesh->invitation_key) {
1680 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1681 meshlink_errno = MESHLINK_EINTERNAL;
1682 pthread_mutex_unlock(&(mesh->mesh_mutex));
1686 f = fopen(filename, "wb");
1689 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1690 meshlink_errno = MESHLINK_ESTORAGE;
1691 pthread_mutex_unlock(&(mesh->mesh_mutex));
1695 chmod(filename, 0600);
1696 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1699 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1702 if(!mesh->invitation_key) {
1703 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1704 meshlink_errno = MESHLINK_ESTORAGE;
1708 pthread_mutex_unlock(&(mesh->mesh_mutex));
1709 return mesh->invitation_key;
1712 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1713 if(!mesh || !node || !address) {
1714 meshlink_errno = MESHLINK_EINVAL;
1718 if(!is_valid_hostname(address)) {
1719 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1720 meshlink_errno = MESHLINK_EINVAL;
1724 if(port && !is_valid_port(port)) {
1725 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1726 meshlink_errno = MESHLINK_EINVAL;
1730 char *canonical_address;
1733 xasprintf(&canonical_address, "%s %s", address, port);
1735 canonical_address = xstrdup(address);
1738 pthread_mutex_lock(&(mesh->mesh_mutex));
1739 bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1740 pthread_mutex_unlock(&(mesh->mesh_mutex));
1742 free(canonical_address);
1746 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1747 return meshlink_set_canonical_address(mesh, mesh->self, address, NULL);
1750 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1752 meshlink_errno = MESHLINK_EINVAL;
1756 char *address = meshlink_get_external_address(mesh);
1764 pthread_mutex_lock(&(mesh->mesh_mutex));
1765 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1766 pthread_mutex_unlock(&(mesh->mesh_mutex));
1772 int meshlink_get_port(meshlink_handle_t *mesh) {
1774 meshlink_errno = MESHLINK_EINVAL;
1779 meshlink_errno = MESHLINK_EINTERNAL;
1783 return atoi(mesh->myport);
1786 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1787 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1788 meshlink_errno = MESHLINK_EINVAL;
1792 if(mesh->myport && port == atoi(mesh->myport)) {
1796 if(!try_bind(port)) {
1797 meshlink_errno = MESHLINK_ENETWORK;
1803 pthread_mutex_lock(&(mesh->mesh_mutex));
1805 if(mesh->threadstarted) {
1806 meshlink_errno = MESHLINK_EINVAL;
1810 close_network_connections(mesh);
1811 exit_configuration(&mesh->config);
1814 snprintf(portstr, sizeof(portstr), "%d", port);
1815 portstr[sizeof(portstr) - 1] = 0;
1817 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1819 init_configuration(&mesh->config);
1821 if(!read_server_config(mesh)) {
1822 meshlink_errno = MESHLINK_ESTORAGE;
1823 } else if(!setup_network(mesh)) {
1824 meshlink_errno = MESHLINK_ENETWORK;
1830 pthread_mutex_unlock(&(mesh->mesh_mutex));
1835 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1837 meshlink_errno = MESHLINK_EINVAL;
1841 pthread_mutex_lock(&(mesh->mesh_mutex));
1843 // Check validity of the new node's name
1844 if(!check_id(name)) {
1845 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1846 meshlink_errno = MESHLINK_EINVAL;
1847 pthread_mutex_unlock(&(mesh->mesh_mutex));
1851 // Ensure no host configuration file with that name exists
1852 char filename[PATH_MAX];
1853 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1855 if(!access(filename, F_OK)) {
1856 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1857 meshlink_errno = MESHLINK_EEXIST;
1858 pthread_mutex_unlock(&(mesh->mesh_mutex));
1862 // Ensure no other nodes know about this name
1863 if(meshlink_get_node(mesh, name)) {
1864 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1865 meshlink_errno = MESHLINK_EEXIST;
1866 pthread_mutex_unlock(&(mesh->mesh_mutex));
1870 // Get the local address
1871 char *address = get_my_hostname(mesh);
1874 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1875 meshlink_errno = MESHLINK_ERESOLV;
1876 pthread_mutex_unlock(&(mesh->mesh_mutex));
1880 if(!refresh_invitation_key(mesh)) {
1881 meshlink_errno = MESHLINK_EINTERNAL;
1882 pthread_mutex_unlock(&(mesh->mesh_mutex));
1888 // Create a hash of the key.
1889 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1890 sha512(fingerprint, strlen(fingerprint), hash);
1891 b64encode_urlsafe(hash, hash, 18);
1893 // Create a random cookie for this invitation.
1895 randomize(cookie, 18);
1897 // Create a filename that doesn't reveal the cookie itself
1898 char buf[18 + strlen(fingerprint)];
1899 char cookiehash[64];
1900 memcpy(buf, cookie, 18);
1901 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1902 sha512(buf, sizeof(buf), cookiehash);
1903 b64encode_urlsafe(cookiehash, cookiehash, 18);
1905 b64encode_urlsafe(cookie, cookie, 18);
1909 // Create a file containing the details of the invitation.
1910 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1911 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1914 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1915 meshlink_errno = MESHLINK_ESTORAGE;
1916 pthread_mutex_unlock(&(mesh->mesh_mutex));
1920 FILE *f = fdopen(ifd, "w");
1926 // Fill in the details.
1927 fprintf(f, "Name = %s\n", name);
1928 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1930 // Copy Broadcast and Mode
1931 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1932 FILE *tc = fopen(filename, "r");
1937 while(fgets(buf, sizeof(buf), tc)) {
1938 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1939 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1942 // Make sure there is a newline character.
1943 if(!strchr(buf, '\n')) {
1951 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1952 meshlink_errno = MESHLINK_ESTORAGE;
1953 pthread_mutex_unlock(&(mesh->mesh_mutex));
1957 fprintf(f, "#---------------------------------------------------------------#\n");
1958 fprintf(f, "Name = %s\n", mesh->self->name);
1960 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1964 // Create an URL from the local address, key hash and cookie
1966 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1969 pthread_mutex_unlock(&(mesh->mesh_mutex));
1973 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1974 if(!mesh || !invitation) {
1975 meshlink_errno = MESHLINK_EINVAL;
1979 pthread_mutex_lock(&(mesh->mesh_mutex));
1981 //Before doing meshlink_join make sure we are not connected to another mesh
1982 if(mesh->threadstarted) {
1983 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1984 meshlink_errno = MESHLINK_EINVAL;
1985 pthread_mutex_unlock(&(mesh->mesh_mutex));
1989 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1990 char copy[strlen(invitation) + 1];
1991 strcpy(copy, invitation);
1993 // Split the invitation URL into hostname, port, key hash and cookie.
1995 char *slash = strchr(copy, '/');
2003 if(strlen(slash) != 48) {
2007 char *address = copy;
2008 char *port = strrchr(address, ':');
2016 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2020 // Generate a throw-away key for the invitation.
2021 ecdsa_t *key = ecdsa_generate();
2024 meshlink_errno = MESHLINK_EINTERNAL;
2025 pthread_mutex_unlock(&(mesh->mesh_mutex));
2029 char *b64key = ecdsa_get_base64_public_key(key);
2033 while(address && *address) {
2034 // We allow commas in the address part to support multiple addresses in one invitation URL.
2035 comma = strchr(address, ',');
2041 // IPv6 address are enclosed in brackets, per RFC 3986
2042 if(*address == '[') {
2044 char *bracket = strchr(address, ']');
2052 if(comma && bracket != comma) {
2057 // Connect to the meshlink daemon mentioned in the URL.
2058 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2061 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2062 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2064 if(mesh->sock == -1) {
2065 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2066 meshlink_errno = MESHLINK_ENETWORK;
2070 set_timeout(mesh->sock, 5000);
2072 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2073 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2074 meshlink_errno = MESHLINK_ENETWORK;
2075 closesocket(mesh->sock);
2083 meshlink_errno = MESHLINK_ERESOLV;
2086 if(mesh->sock != -1 || !comma) {
2093 if(mesh->sock == -1) {
2094 pthread_mutex_unlock(&mesh->mesh_mutex);
2098 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2100 // Tell him we have an invitation, and give him our throw-away key.
2104 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2105 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2106 closesocket(mesh->sock);
2107 meshlink_errno = MESHLINK_ENETWORK;
2108 pthread_mutex_unlock(&(mesh->mesh_mutex));
2114 char hisname[4096] = "";
2115 int code, hismajor, hisminor = 0;
2117 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) {
2118 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2119 closesocket(mesh->sock);
2120 meshlink_errno = MESHLINK_ENETWORK;
2121 pthread_mutex_unlock(&(mesh->mesh_mutex));
2125 // Check if the hash of the key he gave us matches the hash in the URL.
2126 char *fingerprint = mesh->line + 2;
2129 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2130 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2131 meshlink_errno = MESHLINK_EINTERNAL;
2132 pthread_mutex_unlock(&(mesh->mesh_mutex));
2136 if(memcmp(hishash, mesh->hash, 18)) {
2137 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2138 meshlink_errno = MESHLINK_EPEER;
2139 pthread_mutex_unlock(&(mesh->mesh_mutex));
2144 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2147 meshlink_errno = MESHLINK_EINTERNAL;
2148 pthread_mutex_unlock(&(mesh->mesh_mutex));
2152 // Start an SPTPS session
2153 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2154 meshlink_errno = MESHLINK_EINTERNAL;
2155 pthread_mutex_unlock(&(mesh->mesh_mutex));
2159 // Feed rest of input buffer to SPTPS
2160 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2161 meshlink_errno = MESHLINK_EPEER;
2162 pthread_mutex_unlock(&(mesh->mesh_mutex));
2168 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2170 if(errno == EINTR) {
2174 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2175 meshlink_errno = MESHLINK_ENETWORK;
2176 pthread_mutex_unlock(&(mesh->mesh_mutex));
2180 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2181 meshlink_errno = MESHLINK_EPEER;
2182 pthread_mutex_unlock(&(mesh->mesh_mutex));
2187 sptps_stop(&mesh->sptps);
2190 closesocket(mesh->sock);
2192 if(!mesh->success) {
2193 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2194 meshlink_errno = MESHLINK_EPEER;
2195 pthread_mutex_unlock(&(mesh->mesh_mutex));
2199 pthread_mutex_unlock(&(mesh->mesh_mutex));
2203 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2204 meshlink_errno = MESHLINK_EINVAL;
2205 pthread_mutex_unlock(&(mesh->mesh_mutex));
2209 char *meshlink_export(meshlink_handle_t *mesh) {
2211 meshlink_errno = MESHLINK_EINVAL;
2215 pthread_mutex_lock(&(mesh->mesh_mutex));
2217 char filename[PATH_MAX];
2218 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2219 FILE *f = fopen(filename, "r");
2222 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2223 meshlink_errno = MESHLINK_ESTORAGE;
2224 pthread_mutex_unlock(&(mesh->mesh_mutex));
2228 fseek(f, 0, SEEK_END);
2229 int fsize = ftell(f);
2232 size_t len = fsize + 9 + strlen(mesh->self->name);
2233 char *buf = xmalloc(len);
2234 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2236 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2237 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2240 meshlink_errno = MESHLINK_ESTORAGE;
2241 pthread_mutex_unlock(&(mesh->mesh_mutex));
2248 pthread_mutex_unlock(&(mesh->mesh_mutex));
2252 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2253 if(!mesh || !data) {
2254 meshlink_errno = MESHLINK_EINVAL;
2258 pthread_mutex_lock(&(mesh->mesh_mutex));
2260 if(strncmp(data, "Name = ", 7)) {
2261 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2262 meshlink_errno = MESHLINK_EPEER;
2263 pthread_mutex_unlock(&(mesh->mesh_mutex));
2267 char *end = strchr(data + 7, '\n');
2270 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2271 meshlink_errno = MESHLINK_EPEER;
2272 pthread_mutex_unlock(&(mesh->mesh_mutex));
2276 int len = end - (data + 7);
2278 memcpy(name, data + 7, len);
2281 if(!check_id(name)) {
2282 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2283 meshlink_errno = MESHLINK_EPEER;
2284 pthread_mutex_unlock(&(mesh->mesh_mutex));
2288 char filename[PATH_MAX];
2289 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2291 if(!access(filename, F_OK)) {
2292 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2293 meshlink_errno = MESHLINK_EEXIST;
2294 pthread_mutex_unlock(&(mesh->mesh_mutex));
2298 if(errno != ENOENT) {
2299 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2300 meshlink_errno = MESHLINK_ESTORAGE;
2301 pthread_mutex_unlock(&(mesh->mesh_mutex));
2305 FILE *f = fopen(filename, "w");
2308 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2309 meshlink_errno = MESHLINK_ESTORAGE;
2310 pthread_mutex_unlock(&(mesh->mesh_mutex));
2314 fwrite(end + 1, strlen(end + 1), 1, f);
2317 load_all_nodes(mesh);
2319 pthread_mutex_unlock(&(mesh->mesh_mutex));
2323 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2324 if(!mesh || !node) {
2325 meshlink_errno = MESHLINK_EINVAL;
2329 pthread_mutex_lock(&(mesh->mesh_mutex));
2333 n->status.blacklisted = true;
2334 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2336 //Make blacklisting persistent in the config file
2337 append_config_file(mesh, n->name, "blacklisted", "yes");
2339 pthread_mutex_unlock(&(mesh->mesh_mutex));
2343 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2344 if(!mesh || !node) {
2345 meshlink_errno = MESHLINK_EINVAL;
2349 pthread_mutex_lock(&(mesh->mesh_mutex));
2351 node_t *n = (node_t *)node;
2352 n->status.blacklisted = false;
2354 //TODO: remove blacklisted = yes from the config file
2356 pthread_mutex_unlock(&(mesh->mesh_mutex));
2360 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2361 mesh->default_blacklist = blacklist;
2364 /* Hint that a hostname may be found at an address
2365 * See header file for detailed comment.
2367 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2368 if(!mesh || !node || !addr) {
2372 // Ignore hints about ourself.
2373 if((node_t *)node == mesh->self) {
2377 pthread_mutex_lock(&(mesh->mesh_mutex));
2379 char *host = NULL, *port = NULL, *str = NULL;
2380 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2383 xasprintf(&str, "%s %s", host, port);
2385 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2386 modify_config_file(mesh, node->name, "Address", str, 5);
2388 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2396 pthread_mutex_unlock(&(mesh->mesh_mutex));
2397 // @TODO do we want to fire off a connection attempt right away?
2400 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2402 node_t *n = utcp->priv;
2403 meshlink_handle_t *mesh = n->mesh;
2404 return mesh->channel_accept_cb;
2407 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2408 meshlink_channel_t *channel = connection->priv;
2414 node_t *n = channel->node;
2415 meshlink_handle_t *mesh = n->mesh;
2417 if(n->status.destroyed) {
2418 meshlink_channel_close(mesh, channel);
2419 } else if(channel->receive_cb) {
2420 channel->receive_cb(mesh, channel, data, len);
2426 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2427 node_t *n = utcp_connection->utcp->priv;
2433 meshlink_handle_t *mesh = n->mesh;
2435 if(!mesh->channel_accept_cb) {
2439 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2441 channel->c = utcp_connection;
2443 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2444 utcp_accept(utcp_connection, channel_recv, channel);
2450 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2451 node_t *n = utcp->priv;
2453 if(n->status.destroyed) {
2457 meshlink_handle_t *mesh = n->mesh;
2458 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2461 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2462 if(!mesh || !channel) {
2463 meshlink_errno = MESHLINK_EINVAL;
2467 channel->receive_cb = cb;
2470 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2472 node_t *n = (node_t *)source;
2478 utcp_recv(n->utcp, data, len);
2481 static void channel_poll(struct utcp_connection *connection, size_t len) {
2482 meshlink_channel_t *channel = connection->priv;
2488 node_t *n = channel->node;
2489 meshlink_handle_t *mesh = n->mesh;
2491 if(channel->poll_cb) {
2492 channel->poll_cb(mesh, channel, len);
2496 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2498 channel->poll_cb = cb;
2499 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2502 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2504 meshlink_errno = MESHLINK_EINVAL;
2508 pthread_mutex_lock(&mesh->mesh_mutex);
2509 mesh->channel_accept_cb = cb;
2510 mesh->receive_cb = channel_receive;
2512 for splay_each(node_t, n, mesh->nodes) {
2513 if(!n->utcp && n != mesh->self) {
2514 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2518 pthread_mutex_unlock(&mesh->mesh_mutex);
2521 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) {
2523 abort(); // TODO: handle non-NULL data
2526 if(!mesh || !node) {
2527 meshlink_errno = MESHLINK_EINVAL;
2531 node_t *n = (node_t *)node;
2534 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2535 mesh->receive_cb = channel_receive;
2538 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2543 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2545 channel->receive_cb = cb;
2546 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2549 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2557 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) {
2558 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2561 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2562 if(!mesh || !channel) {
2563 meshlink_errno = MESHLINK_EINVAL;
2567 utcp_shutdown(channel->c, direction);
2570 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2571 if(!mesh || !channel) {
2572 meshlink_errno = MESHLINK_EINVAL;
2576 utcp_close(channel->c);
2580 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2581 if(!mesh || !channel) {
2582 meshlink_errno = MESHLINK_EINVAL;
2591 meshlink_errno = MESHLINK_EINVAL;
2595 // TODO: more finegrained locking.
2596 // Ideally we want to put the data into the UTCP connection's send buffer.
2597 // Then, preferrably only if there is room in the receiver window,
2598 // kick the meshlink thread to go send packets.
2600 pthread_mutex_lock(&mesh->mesh_mutex);
2601 ssize_t retval = utcp_send(channel->c, data, len);
2602 pthread_mutex_unlock(&mesh->mesh_mutex);
2605 meshlink_errno = MESHLINK_ENETWORK;
2611 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2612 if(!mesh || !channel) {
2613 meshlink_errno = MESHLINK_EINVAL;
2617 return channel->c->flags;
2620 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2621 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2622 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2625 if(mesh->node_status_cb) {
2626 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2630 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2632 meshlink_errno = MESHLINK_EINVAL;
2636 pthread_mutex_lock(&mesh->mesh_mutex);
2638 if(mesh->discovery == enable) {
2642 if(mesh->threadstarted) {
2644 discovery_start(mesh);
2646 discovery_stop(mesh);
2650 mesh->discovery = enable;
2653 pthread_mutex_unlock(&mesh->mesh_mutex);
2656 static void __attribute__((constructor)) meshlink_init(void) {
2659 randomize(&seed, sizeof(seed));
2663 static void __attribute__((destructor)) meshlink_exit(void) {
2667 /// Device class traits
2668 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2669 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2670 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2671 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2672 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN