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 {"Address", VAR_HOST | VAR_MULTIPLE},
63 {"ECDSAPublicKey", VAR_HOST},
68 static bool fcopy(FILE *out, const char *filename) {
69 FILE *in = fopen(filename, "r");
72 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
79 while((len = fread(buf, 1, sizeof(buf), in))) {
80 fwrite(buf, len, 1, out);
87 static int rstrip(char *value) {
88 int len = strlen(value);
90 while(len && strchr("\t\r\n ", value[len - 1])) {
97 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
100 if(!filename || (*hostname && *port)) {
104 FILE *f = fopen(filename, "r");
110 while(fgets(line, sizeof(line), f)) {
116 p += strcspn(p, "\t =");
122 q = p + strspn(p, "\t ");
125 q += 1 + strspn(q + 1, "\t ");
128 // q is now pointing to the hostname
130 p = q + strcspn(q, "\t ");
136 p += strspn(p, "\t ");
137 p[strcspn(p, "\t ")] = 0;
138 // p is now pointing to the port
140 // Check that the hostname is a symbolic name (it's not a numeric IPv4 or IPv6 address)
141 if(!q[strspn(q, "0123456789.")] || strchr(q, ':')) {
145 if(!*port && !strcasecmp(line, "Port")) {
147 } else if(!*hostname && !strcasecmp(line, "Address")) {
148 *hostname = xstrdup(q);
156 if(*hostname && *port) {
164 static bool is_valid_hostname(const char *hostname) {
165 for(const char *p = hostname; *p; p++) {
166 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
174 static void set_timeout(int sock, int timeout) {
179 tv.tv_sec = timeout / 1000;
180 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
182 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
183 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
186 // Find out what local address a socket would use if we connect to the given address.
187 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
188 // of both endpoints, but this will actually not send any UDP packet.
189 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
190 struct addrinfo *rai = NULL;
191 const struct addrinfo hint = {
192 .ai_family = AF_UNSPEC,
193 .ai_socktype = SOCK_DGRAM,
194 .ai_protocol = IPPROTO_UDP,
197 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
201 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
208 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
215 struct sockaddr_storage sn;
216 socklen_t sl = sizeof(sn);
218 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
222 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
229 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
230 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
233 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
234 char *hostname = NULL;
236 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
237 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
238 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
241 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
242 if(family != AF_UNSPEC && aip->ai_family != family) {
246 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
249 set_timeout(s, 5000);
251 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
258 send(s, request, sizeof(request) - 1, 0);
259 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
264 if(line[len - 1] == '\n') {
268 char *p = strrchr(line, '\n');
271 hostname = xstrdup(p + 1);
287 // Check that the hostname is reasonable
288 if(hostname && !is_valid_hostname(hostname)) {
293 // If there is no hostname, determine the address used for an outgoing connection.
295 char localaddr[NI_MAXHOST];
296 bool success = false;
298 if(family == AF_INET) {
299 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
300 } else if(family == AF_INET6) {
301 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
305 hostname = xstrdup(localaddr);
310 meshlink_errno = MESHLINK_ERESOLV;
316 // This gets the hostname part for use in invitation URLs
317 static char *get_my_hostname(meshlink_handle_t *mesh) {
318 char *hostname[2] = {NULL};
320 char *hostport = NULL;
321 char *name = mesh->self->name;
322 char filename[PATH_MAX] = "";
324 // Use first Address statement in own host config file
325 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
326 scan_for_hostname(filename, &hostname[0], &port);
332 hostname[0] = meshlink_get_external_address_for_family(mesh, AF_INET);
333 hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET6);
335 if(!hostname[0] && !hostname[1]) {
339 if(hostname[0] && hostname[1] && !strcmp(hostname[0], hostname[1])) {
344 port = xstrdup(mesh->myport);
346 for(int i = 0; i < 2; i++) {
349 xasprintf(&tmphostport, "%s %s", hostname[i], port);
350 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
357 for(int i = 0; i < 2; i++) {
363 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]" : "%s%s%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i]);
366 hostport = newhostport;
371 xasprintf(&newhostport, "%s:%s", hostport, port);
374 hostport = newhostport;
380 static char *get_line(const char **data) {
381 if(!data || !*data) {
390 static char line[1024];
391 const char *end = strchr(*data, '\n');
392 size_t len = end ? (size_t)(end - *data) : strlen(*data);
394 if(len >= sizeof(line)) {
395 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
399 if(len && !isprint(**data)) {
403 memcpy(line, *data, len);
415 static char *get_value(const char *data, const char *var) {
416 char *line = get_line(&data);
422 char *sep = line + strcspn(line, " \t=");
423 char *val = sep + strspn(sep, " \t");
426 val += 1 + strspn(val + 1, " \t");
431 if(strcasecmp(line, var)) {
438 static bool try_bind(int port) {
439 struct addrinfo *ai = NULL;
440 struct addrinfo hint = {
441 .ai_flags = AI_PASSIVE,
442 .ai_family = AF_UNSPEC,
443 .ai_socktype = SOCK_STREAM,
444 .ai_protocol = IPPROTO_TCP,
448 snprintf(portstr, sizeof(portstr), "%d", port);
450 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
455 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
462 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
477 int check_port(meshlink_handle_t *mesh) {
478 for(int i = 0; i < 1000; i++) {
479 int port = 0x1000 + (rand() & 0x7fff);
482 char filename[PATH_MAX];
483 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
484 FILE *f = fopen(filename, "a");
487 meshlink_errno = MESHLINK_ESTORAGE;
488 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
492 fprintf(f, "Port = %d\n", port);
498 meshlink_errno = MESHLINK_ENETWORK;
499 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
503 static bool finalize_join(meshlink_handle_t *mesh) {
504 char *name = xstrdup(get_value(mesh->data, "Name"));
507 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
511 if(!check_id(name)) {
512 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
516 char filename[PATH_MAX];
517 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
519 FILE *f = fopen(filename, "w");
522 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
526 fprintf(f, "Name = %s\n", name);
528 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
529 FILE *fh = fopen(filename, "w");
532 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
537 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
538 // Other chunks go unfiltered to their respective host config files
539 const char *p = mesh->data;
542 while((l = get_line(&p))) {
548 // Split line into variable and value
549 int len = strcspn(l, "\t =");
551 value += strspn(value, "\t ");
555 value += strspn(value, "\t ");
561 if(!strcasecmp(l, "Name"))
562 if(strcmp(value, name)) {
566 } else if(!strcasecmp(l, "NetName")) {
570 // Check the list of known variables
574 for(i = 0; variables[i].name; i++) {
575 if(strcasecmp(l, variables[i].name)) {
583 // Ignore unknown and unsafe variables
585 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
587 } else if(!(variables[i].type & VAR_SAFE)) {
588 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
592 // Copy the safe variable to the right config file
593 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
598 while(l && !strcasecmp(l, "Name")) {
599 if(!check_id(value)) {
600 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
604 if(!strcmp(value, name)) {
605 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
609 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
610 f = fopen(filename, "w");
613 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
617 while((l = get_line(&p))) {
618 if(!strcmp(l, "#---------------------------------------------------------------#")) {
622 int len = strcspn(l, "\t =");
624 if(len == 4 && !strncasecmp(l, "Name", 4)) {
626 value += strspn(value, "\t ");
630 value += strspn(value, "\t ");
644 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
651 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
652 fprintf(fh, "Port = %s\n", mesh->myport);
656 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
659 free(mesh->self->name);
660 free(mesh->self->connection->name);
661 mesh->self->name = xstrdup(name);
662 mesh->self->connection->name = name;
664 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
666 load_all_nodes(mesh);
671 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
673 meshlink_handle_t *mesh = handle;
674 const char *ptr = data;
677 int result = send(mesh->sock, ptr, len, 0);
679 if(result == -1 && errno == EINTR) {
681 } else if(result <= 0) {
692 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
693 meshlink_handle_t *mesh = handle;
696 case SPTPS_HANDSHAKE:
697 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
700 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
701 memcpy(mesh->data + mesh->thedatalen, msg, len);
702 mesh->thedatalen += len;
703 mesh->data[mesh->thedatalen] = 0;
707 mesh->thedatalen = 0;
708 return finalize_join(mesh);
711 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
712 shutdown(mesh->sock, SHUT_RDWR);
713 mesh->success = true;
723 static bool recvline(meshlink_handle_t *mesh, size_t len) {
724 char *newline = NULL;
730 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
731 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
733 if(result == -1 && errno == EINTR) {
735 } else if(result <= 0) {
739 mesh->blen += result;
742 if((size_t)(newline - mesh->buffer) >= len) {
746 len = newline - mesh->buffer;
748 memcpy(mesh->line, mesh->buffer, len);
750 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
751 mesh->blen -= len + 1;
755 static bool sendline(int fd, char *format, ...) {
756 static char buffer[4096];
761 va_start(ap, format);
762 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
765 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
773 int result = send(fd, p, blen, MSG_NOSIGNAL);
775 if(result == -1 && errno == EINTR) {
777 } else if(result <= 0) {
788 static const char *errstr[] = {
789 [MESHLINK_OK] = "No error",
790 [MESHLINK_EINVAL] = "Invalid argument",
791 [MESHLINK_ENOMEM] = "Out of memory",
792 [MESHLINK_ENOENT] = "No such node",
793 [MESHLINK_EEXIST] = "Node already exists",
794 [MESHLINK_EINTERNAL] = "Internal error",
795 [MESHLINK_ERESOLV] = "Could not resolve hostname",
796 [MESHLINK_ESTORAGE] = "Storage error",
797 [MESHLINK_ENETWORK] = "Network error",
798 [MESHLINK_EPEER] = "Error communicating with peer",
801 const char *meshlink_strerror(meshlink_errno_t err) {
802 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
803 return "Invalid error code";
809 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
812 char pubname[PATH_MAX], privname[PATH_MAX];
814 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
816 if(!(key = ecdsa_generate())) {
817 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
818 meshlink_errno = MESHLINK_EINTERNAL;
821 logger(mesh, MESHLINK_DEBUG, "Done.\n");
824 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
825 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
826 meshlink_errno = MESHLINK_ESTORAGE;
830 f = fopen(privname, "wb");
833 meshlink_errno = MESHLINK_ESTORAGE;
838 fchmod(fileno(f), 0600);
841 if(!ecdsa_write_pem_private_key(key, f)) {
842 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
845 meshlink_errno = MESHLINK_EINTERNAL;
851 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
852 f = fopen(pubname, "a");
855 meshlink_errno = MESHLINK_ESTORAGE;
859 char *pubkey = ecdsa_get_base64_public_key(key);
860 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
869 static struct timeval idle(event_loop_t *loop, void *data) {
871 meshlink_handle_t *mesh = data;
872 struct timeval t, tmin = {3600, 0};
874 for splay_each(node_t, n, mesh->nodes) {
879 t = utcp_timeout(n->utcp);
881 if(timercmp(&t, &tmin, <)) {
889 // Get our local address(es) by simulating connecting to an Internet host.
890 static void add_local_addresses(meshlink_handle_t *mesh) {
891 char host[NI_MAXHOST];
892 char entry[MAX_STRING_SIZE];
896 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
897 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
898 append_config_file(mesh, mesh->name, "Address", entry);
903 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
904 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
905 append_config_file(mesh, mesh->name, "Address", entry);
909 static bool meshlink_setup(meshlink_handle_t *mesh) {
910 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
911 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
912 meshlink_errno = MESHLINK_ESTORAGE;
916 char filename[PATH_MAX];
917 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
919 if(mkdir(filename, 0777) && errno != EEXIST) {
920 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
921 meshlink_errno = MESHLINK_ESTORAGE;
925 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
927 if(!access(filename, F_OK)) {
928 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
929 meshlink_errno = MESHLINK_EEXIST;
933 FILE *f = fopen(filename, "w");
936 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
937 meshlink_errno = MESHLINK_ESTORAGE;
941 fprintf(f, "Name = %s\n", mesh->name);
944 if(!ecdsa_keygen(mesh)) {
945 meshlink_errno = MESHLINK_EINTERNAL;
950 if(check_port(mesh) == 0) {
951 meshlink_errno = MESHLINK_ENETWORK;
959 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
960 // Validate arguments provided by the application
961 bool usingname = false;
963 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
965 if(!confbase || !*confbase) {
966 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
967 meshlink_errno = MESHLINK_EINVAL;
971 if(!appname || !*appname) {
972 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
973 meshlink_errno = MESHLINK_EINVAL;
977 if(!name || !*name) {
978 logger(NULL, MESHLINK_ERROR, "No name given!\n");
980 } else { //check name only if there is a name != NULL
982 if(!check_id(name)) {
983 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
984 meshlink_errno = MESHLINK_EINVAL;
991 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
992 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
993 meshlink_errno = MESHLINK_EINVAL;
997 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
998 mesh->confbase = xstrdup(confbase);
999 mesh->appname = xstrdup(appname);
1000 mesh->devclass = devclass;
1001 mesh->discovery = true;
1004 mesh->name = xstrdup(name);
1008 pthread_mutexattr_t attr;
1009 pthread_mutexattr_init(&attr);
1010 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1011 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1013 mesh->threadstarted = false;
1014 event_loop_init(&mesh->loop);
1015 mesh->loop.data = mesh;
1017 meshlink_queue_init(&mesh->outpacketqueue);
1019 // Check whether meshlink.conf already exists
1021 char filename[PATH_MAX];
1022 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1024 if(access(filename, R_OK)) {
1025 if(errno == ENOENT) {
1026 // If not, create it
1027 if(!meshlink_setup(mesh)) {
1028 // meshlink_errno is set by meshlink_setup()
1032 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1033 meshlink_close(mesh);
1034 meshlink_errno = MESHLINK_ESTORAGE;
1039 // Read the configuration
1041 init_configuration(&mesh->config);
1043 if(!read_server_config(mesh)) {
1044 meshlink_close(mesh);
1045 meshlink_errno = MESHLINK_ESTORAGE;
1050 struct WSAData wsa_state;
1052 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1056 // Setup up everything
1057 // TODO: we should not open listening sockets yet
1059 if(!setup_network(mesh)) {
1060 meshlink_close(mesh);
1061 meshlink_errno = MESHLINK_ENETWORK;
1065 add_local_addresses(mesh);
1067 idle_set(&mesh->loop, idle, mesh);
1069 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1073 static void *meshlink_main_loop(void *arg) {
1074 meshlink_handle_t *mesh = arg;
1076 pthread_mutex_lock(&(mesh->mesh_mutex));
1078 try_outgoing_connections(mesh);
1080 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1082 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1084 pthread_mutex_unlock(&(mesh->mesh_mutex));
1088 bool meshlink_start(meshlink_handle_t *mesh) {
1090 meshlink_errno = MESHLINK_EINVAL;
1094 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1096 pthread_mutex_lock(&(mesh->mesh_mutex));
1098 if(mesh->threadstarted) {
1099 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1100 pthread_mutex_unlock(&(mesh->mesh_mutex));
1104 if(mesh->listen_socket[0].tcp.fd < 0) {
1105 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1106 meshlink_errno = MESHLINK_ENETWORK;
1110 mesh->thedatalen = 0;
1112 // TODO: open listening sockets first
1114 //Check that a valid name is set
1116 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1117 meshlink_errno = MESHLINK_EINVAL;
1118 pthread_mutex_unlock(&(mesh->mesh_mutex));
1122 // Start the main thread
1124 event_loop_start(&mesh->loop);
1126 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1127 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1128 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1129 meshlink_errno = MESHLINK_EINTERNAL;
1130 pthread_mutex_unlock(&(mesh->mesh_mutex));
1134 mesh->threadstarted = true;
1136 if(mesh->discovery) {
1137 discovery_start(mesh);
1140 pthread_mutex_unlock(&(mesh->mesh_mutex));
1144 void meshlink_stop(meshlink_handle_t *mesh) {
1146 meshlink_errno = MESHLINK_EINVAL;
1150 pthread_mutex_lock(&(mesh->mesh_mutex));
1151 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1154 if(mesh->discovery) {
1155 discovery_stop(mesh);
1158 // Shut down the main thread
1159 event_loop_stop(&mesh->loop);
1161 // Send ourselves a UDP packet to kick the event loop
1162 for(int i = 0; i < mesh->listen_sockets; i++) {
1164 socklen_t salen = sizeof(sa.sa);
1166 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1167 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1171 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1172 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1176 // Wait for the main thread to finish
1177 pthread_mutex_unlock(&(mesh->mesh_mutex));
1178 pthread_join(mesh->thread, NULL);
1179 pthread_mutex_lock(&(mesh->mesh_mutex));
1181 mesh->threadstarted = false;
1183 // Close all metaconnections
1184 if(mesh->connections) {
1185 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1187 connection_t *c = node->data;
1189 terminate_connection(mesh, c, false);
1193 if(mesh->outgoings) {
1194 list_delete_list(mesh->outgoings);
1197 mesh->outgoings = NULL;
1199 pthread_mutex_unlock(&(mesh->mesh_mutex));
1202 void meshlink_close(meshlink_handle_t *mesh) {
1203 if(!mesh || !mesh->confbase) {
1204 meshlink_errno = MESHLINK_EINVAL;
1208 // stop can be called even if mesh has not been started
1209 meshlink_stop(mesh);
1211 // lock is not released after this
1212 pthread_mutex_lock(&(mesh->mesh_mutex));
1214 // Close and free all resources used.
1216 close_network_connections(mesh);
1218 logger(mesh, MESHLINK_INFO, "Terminating");
1220 exit_configuration(&mesh->config);
1221 event_loop_exit(&mesh->loop);
1225 if(mesh->confbase) {
1231 ecdsa_free(mesh->invitation_key);
1234 free(mesh->appname);
1235 free(mesh->confbase);
1236 pthread_mutex_destroy(&(mesh->mesh_mutex));
1238 memset(mesh, 0, sizeof(*mesh));
1243 static void deltree(const char *dirname) {
1244 DIR *d = opendir(dirname);
1249 while((ent = readdir(d))) {
1250 if(ent->d_name[0] == '.') {
1254 char filename[PATH_MAX];
1255 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1257 if(unlink(filename)) {
1269 bool meshlink_destroy(const char *confbase) {
1271 meshlink_errno = MESHLINK_EINVAL;
1275 char filename[PATH_MAX];
1276 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1278 if(unlink(filename)) {
1279 if(errno == ENOENT) {
1280 meshlink_errno = MESHLINK_ENOENT;
1283 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1284 meshlink_errno = MESHLINK_ESTORAGE;
1294 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1296 meshlink_errno = MESHLINK_EINVAL;
1300 pthread_mutex_lock(&(mesh->mesh_mutex));
1301 mesh->receive_cb = cb;
1302 pthread_mutex_unlock(&(mesh->mesh_mutex));
1305 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1307 meshlink_errno = MESHLINK_EINVAL;
1311 pthread_mutex_lock(&(mesh->mesh_mutex));
1312 mesh->node_status_cb = cb;
1313 pthread_mutex_unlock(&(mesh->mesh_mutex));
1316 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1318 pthread_mutex_lock(&(mesh->mesh_mutex));
1320 mesh->log_level = cb ? level : 0;
1321 pthread_mutex_unlock(&(mesh->mesh_mutex));
1324 global_log_level = cb ? level : 0;
1328 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1329 meshlink_packethdr_t *hdr;
1331 // Validate arguments
1332 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1333 meshlink_errno = MESHLINK_EINVAL;
1342 meshlink_errno = MESHLINK_EINVAL;
1346 // Prepare the packet
1347 vpn_packet_t *packet = malloc(sizeof(*packet));
1350 meshlink_errno = MESHLINK_ENOMEM;
1354 packet->probe = false;
1355 packet->tcp = false;
1356 packet->len = len + sizeof(*hdr);
1358 hdr = (meshlink_packethdr_t *)packet->data;
1359 memset(hdr, 0, sizeof(*hdr));
1360 // leave the last byte as 0 to make sure strings are always
1361 // null-terminated if they are longer than the buffer
1362 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1363 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1365 memcpy(packet->data + sizeof(*hdr), data, len);
1368 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1370 meshlink_errno = MESHLINK_ENOMEM;
1374 // Notify event loop
1375 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1380 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1382 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1388 mesh->self->in_packets++;
1389 mesh->self->in_bytes += packet->len;
1390 route(mesh, mesh->self, packet);
1393 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1394 if(!mesh || !destination) {
1395 meshlink_errno = MESHLINK_EINVAL;
1399 pthread_mutex_lock(&(mesh->mesh_mutex));
1401 node_t *n = (node_t *)destination;
1403 if(!n->status.reachable) {
1404 pthread_mutex_unlock(&(mesh->mesh_mutex));
1407 } else if(n->mtuprobes > 30 && n->minmtu) {
1408 pthread_mutex_unlock(&(mesh->mesh_mutex));
1411 pthread_mutex_unlock(&(mesh->mesh_mutex));
1416 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1417 if(!mesh || !node) {
1418 meshlink_errno = MESHLINK_EINVAL;
1422 pthread_mutex_lock(&(mesh->mesh_mutex));
1424 node_t *n = (node_t *)node;
1426 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1427 meshlink_errno = MESHLINK_EINTERNAL;
1428 pthread_mutex_unlock(&(mesh->mesh_mutex));
1432 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1435 meshlink_errno = MESHLINK_EINTERNAL;
1438 pthread_mutex_unlock(&(mesh->mesh_mutex));
1442 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1444 meshlink_errno = MESHLINK_EINVAL;
1448 return (meshlink_node_t *)mesh->self;
1451 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1452 if(!mesh || !name) {
1453 meshlink_errno = MESHLINK_EINVAL;
1457 meshlink_node_t *node = NULL;
1459 pthread_mutex_lock(&(mesh->mesh_mutex));
1460 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1461 pthread_mutex_unlock(&(mesh->mesh_mutex));
1465 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1466 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1467 meshlink_errno = MESHLINK_EINVAL;
1471 meshlink_node_t **result;
1474 pthread_mutex_lock(&(mesh->mesh_mutex));
1476 *nmemb = mesh->nodes->count;
1477 result = realloc(nodes, *nmemb * sizeof(*nodes));
1480 meshlink_node_t **p = result;
1482 for splay_each(node_t, n, mesh->nodes) {
1483 *p++ = (meshlink_node_t *)n;
1488 meshlink_errno = MESHLINK_ENOMEM;
1491 pthread_mutex_unlock(&(mesh->mesh_mutex));
1496 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1497 if(!mesh || !data || !len || !signature || !siglen) {
1498 meshlink_errno = MESHLINK_EINVAL;
1502 if(*siglen < MESHLINK_SIGLEN) {
1503 meshlink_errno = MESHLINK_EINVAL;
1507 pthread_mutex_lock(&(mesh->mesh_mutex));
1509 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1510 meshlink_errno = MESHLINK_EINTERNAL;
1511 pthread_mutex_unlock(&(mesh->mesh_mutex));
1515 *siglen = MESHLINK_SIGLEN;
1516 pthread_mutex_unlock(&(mesh->mesh_mutex));
1520 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1521 if(!mesh || !data || !len || !signature) {
1522 meshlink_errno = MESHLINK_EINVAL;
1526 if(siglen != MESHLINK_SIGLEN) {
1527 meshlink_errno = MESHLINK_EINVAL;
1531 pthread_mutex_lock(&(mesh->mesh_mutex));
1535 struct node_t *n = (struct node_t *)source;
1536 node_read_ecdsa_public_key(mesh, n);
1539 meshlink_errno = MESHLINK_EINTERNAL;
1542 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1545 pthread_mutex_unlock(&(mesh->mesh_mutex));
1549 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1550 char filename[PATH_MAX];
1552 pthread_mutex_lock(&(mesh->mesh_mutex));
1554 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1556 if(mkdir(filename, 0700) && errno != EEXIST) {
1557 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1558 meshlink_errno = MESHLINK_ESTORAGE;
1559 pthread_mutex_unlock(&(mesh->mesh_mutex));
1563 // Count the number of valid invitations, clean up old ones
1564 DIR *dir = opendir(filename);
1567 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1568 meshlink_errno = MESHLINK_ESTORAGE;
1569 pthread_mutex_unlock(&(mesh->mesh_mutex));
1576 time_t deadline = time(NULL) - 604800; // 1 week in the past
1578 while((ent = readdir(dir))) {
1579 if(strlen(ent->d_name) != 24) {
1583 char invname[PATH_MAX];
1586 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1587 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1591 if(!stat(invname, &st)) {
1592 if(mesh->invitation_key && deadline < st.st_mtime) {
1598 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1604 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1606 meshlink_errno = MESHLINK_ESTORAGE;
1607 pthread_mutex_unlock(&(mesh->mesh_mutex));
1613 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1615 // Remove the key if there are no outstanding invitations.
1619 if(mesh->invitation_key) {
1620 ecdsa_free(mesh->invitation_key);
1621 mesh->invitation_key = NULL;
1625 if(mesh->invitation_key) {
1626 pthread_mutex_unlock(&(mesh->mesh_mutex));
1630 // Create a new key if necessary.
1631 FILE *f = fopen(filename, "rb");
1634 if(errno != ENOENT) {
1635 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1636 meshlink_errno = MESHLINK_ESTORAGE;
1637 pthread_mutex_unlock(&(mesh->mesh_mutex));
1641 mesh->invitation_key = ecdsa_generate();
1643 if(!mesh->invitation_key) {
1644 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1645 meshlink_errno = MESHLINK_EINTERNAL;
1646 pthread_mutex_unlock(&(mesh->mesh_mutex));
1650 f = fopen(filename, "wb");
1653 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1654 meshlink_errno = MESHLINK_ESTORAGE;
1655 pthread_mutex_unlock(&(mesh->mesh_mutex));
1659 chmod(filename, 0600);
1660 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1663 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1666 if(!mesh->invitation_key) {
1667 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1668 meshlink_errno = MESHLINK_ESTORAGE;
1672 pthread_mutex_unlock(&(mesh->mesh_mutex));
1673 return mesh->invitation_key;
1676 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1677 if(!mesh || !address) {
1678 meshlink_errno = MESHLINK_EINVAL;
1682 if(!is_valid_hostname(address)) {
1683 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1684 meshlink_errno = MESHLINK_EINVAL;
1690 pthread_mutex_lock(&(mesh->mesh_mutex));
1691 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1692 pthread_mutex_unlock(&(mesh->mesh_mutex));
1697 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1699 meshlink_errno = MESHLINK_EINVAL;
1703 char *address = meshlink_get_external_address(mesh);
1711 pthread_mutex_lock(&(mesh->mesh_mutex));
1712 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1713 pthread_mutex_unlock(&(mesh->mesh_mutex));
1719 int meshlink_get_port(meshlink_handle_t *mesh) {
1721 meshlink_errno = MESHLINK_EINVAL;
1726 meshlink_errno = MESHLINK_EINTERNAL;
1730 return atoi(mesh->myport);
1733 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1734 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1735 meshlink_errno = MESHLINK_EINVAL;
1739 if(mesh->myport && port == atoi(mesh->myport)) {
1743 if(!try_bind(port)) {
1744 meshlink_errno = MESHLINK_ENETWORK;
1750 pthread_mutex_lock(&(mesh->mesh_mutex));
1752 if(mesh->threadstarted) {
1753 meshlink_errno = MESHLINK_EINVAL;
1757 close_network_connections(mesh);
1758 exit_configuration(&mesh->config);
1761 snprintf(portstr, sizeof(portstr), "%d", port);
1762 portstr[sizeof(portstr) - 1] = 0;
1764 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1766 init_configuration(&mesh->config);
1768 if(!read_server_config(mesh)) {
1769 meshlink_errno = MESHLINK_ESTORAGE;
1770 } else if(!setup_network(mesh)) {
1771 meshlink_errno = MESHLINK_ENETWORK;
1777 pthread_mutex_unlock(&(mesh->mesh_mutex));
1782 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1784 meshlink_errno = MESHLINK_EINVAL;
1788 pthread_mutex_lock(&(mesh->mesh_mutex));
1790 // Check validity of the new node's name
1791 if(!check_id(name)) {
1792 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1793 meshlink_errno = MESHLINK_EINVAL;
1794 pthread_mutex_unlock(&(mesh->mesh_mutex));
1798 // Ensure no host configuration file with that name exists
1799 char filename[PATH_MAX];
1800 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1802 if(!access(filename, F_OK)) {
1803 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1804 meshlink_errno = MESHLINK_EEXIST;
1805 pthread_mutex_unlock(&(mesh->mesh_mutex));
1809 // Ensure no other nodes know about this name
1810 if(meshlink_get_node(mesh, name)) {
1811 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1812 meshlink_errno = MESHLINK_EEXIST;
1813 pthread_mutex_unlock(&(mesh->mesh_mutex));
1817 // Get the local address
1818 char *address = get_my_hostname(mesh);
1821 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1822 meshlink_errno = MESHLINK_ERESOLV;
1823 pthread_mutex_unlock(&(mesh->mesh_mutex));
1827 if(!refresh_invitation_key(mesh)) {
1828 meshlink_errno = MESHLINK_EINTERNAL;
1829 pthread_mutex_unlock(&(mesh->mesh_mutex));
1835 // Create a hash of the key.
1836 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1837 sha512(fingerprint, strlen(fingerprint), hash);
1838 b64encode_urlsafe(hash, hash, 18);
1840 // Create a random cookie for this invitation.
1842 randomize(cookie, 18);
1844 // Create a filename that doesn't reveal the cookie itself
1845 char buf[18 + strlen(fingerprint)];
1846 char cookiehash[64];
1847 memcpy(buf, cookie, 18);
1848 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1849 sha512(buf, sizeof(buf), cookiehash);
1850 b64encode_urlsafe(cookiehash, cookiehash, 18);
1852 b64encode_urlsafe(cookie, cookie, 18);
1856 // Create a file containing the details of the invitation.
1857 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1858 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1861 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1862 meshlink_errno = MESHLINK_ESTORAGE;
1863 pthread_mutex_unlock(&(mesh->mesh_mutex));
1867 FILE *f = fdopen(ifd, "w");
1873 // Fill in the details.
1874 fprintf(f, "Name = %s\n", name);
1875 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1877 // Copy Broadcast and Mode
1878 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1879 FILE *tc = fopen(filename, "r");
1884 while(fgets(buf, sizeof(buf), tc)) {
1885 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1886 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1889 // Make sure there is a newline character.
1890 if(!strchr(buf, '\n')) {
1898 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1899 meshlink_errno = MESHLINK_ESTORAGE;
1900 pthread_mutex_unlock(&(mesh->mesh_mutex));
1904 fprintf(f, "#---------------------------------------------------------------#\n");
1905 fprintf(f, "Name = %s\n", mesh->self->name);
1907 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1911 // Create an URL from the local address, key hash and cookie
1913 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1916 pthread_mutex_unlock(&(mesh->mesh_mutex));
1920 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1921 if(!mesh || !invitation) {
1922 meshlink_errno = MESHLINK_EINVAL;
1926 pthread_mutex_lock(&(mesh->mesh_mutex));
1928 //Before doing meshlink_join make sure we are not connected to another mesh
1929 if(mesh->threadstarted) {
1930 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1931 meshlink_errno = MESHLINK_EINVAL;
1932 pthread_mutex_unlock(&(mesh->mesh_mutex));
1936 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1937 char copy[strlen(invitation) + 1];
1938 strcpy(copy, invitation);
1940 // Split the invitation URL into hostname, port, key hash and cookie.
1942 char *slash = strchr(copy, '/');
1950 if(strlen(slash) != 48) {
1954 char *address = copy;
1955 char *port = strrchr(address, ':');
1963 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
1967 // Generate a throw-away key for the invitation.
1968 ecdsa_t *key = ecdsa_generate();
1971 meshlink_errno = MESHLINK_EINTERNAL;
1972 pthread_mutex_unlock(&(mesh->mesh_mutex));
1976 char *b64key = ecdsa_get_base64_public_key(key);
1980 while(address && *address) {
1981 // We allow commas in the address part to support multiple addresses in one invitation URL.
1982 comma = strchr(address, ',');
1988 // IPv6 address are enclosed in brackets, per RFC 3986
1989 if(*address == '[') {
1991 char *bracket = strchr(address, ']');
1999 if(comma && bracket != comma) {
2004 // Connect to the meshlink daemon mentioned in the URL.
2005 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2008 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2009 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2011 if(mesh->sock == -1) {
2012 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2013 meshlink_errno = MESHLINK_ENETWORK;
2017 set_timeout(mesh->sock, 5000);
2019 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2020 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2021 meshlink_errno = MESHLINK_ENETWORK;
2022 closesocket(mesh->sock);
2030 meshlink_errno = MESHLINK_ERESOLV;
2033 if(mesh->sock != -1 || !comma) {
2040 if(mesh->sock == -1) {
2041 pthread_mutex_unlock(&mesh->mesh_mutex);
2045 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2047 // Tell him we have an invitation, and give him our throw-away key.
2051 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2052 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2053 closesocket(mesh->sock);
2054 meshlink_errno = MESHLINK_ENETWORK;
2055 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 char hisname[4096] = "";
2062 int code, hismajor, hisminor = 0;
2064 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) {
2065 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2066 closesocket(mesh->sock);
2067 meshlink_errno = MESHLINK_ENETWORK;
2068 pthread_mutex_unlock(&(mesh->mesh_mutex));
2072 // Check if the hash of the key he gave us matches the hash in the URL.
2073 char *fingerprint = mesh->line + 2;
2076 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2077 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2078 meshlink_errno = MESHLINK_EINTERNAL;
2079 pthread_mutex_unlock(&(mesh->mesh_mutex));
2083 if(memcmp(hishash, mesh->hash, 18)) {
2084 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2085 meshlink_errno = MESHLINK_EPEER;
2086 pthread_mutex_unlock(&(mesh->mesh_mutex));
2091 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2094 meshlink_errno = MESHLINK_EINTERNAL;
2095 pthread_mutex_unlock(&(mesh->mesh_mutex));
2099 // Start an SPTPS session
2100 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2101 meshlink_errno = MESHLINK_EINTERNAL;
2102 pthread_mutex_unlock(&(mesh->mesh_mutex));
2106 // Feed rest of input buffer to SPTPS
2107 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2108 meshlink_errno = MESHLINK_EPEER;
2109 pthread_mutex_unlock(&(mesh->mesh_mutex));
2115 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2117 if(errno == EINTR) {
2121 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2122 meshlink_errno = MESHLINK_ENETWORK;
2123 pthread_mutex_unlock(&(mesh->mesh_mutex));
2127 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2128 meshlink_errno = MESHLINK_EPEER;
2129 pthread_mutex_unlock(&(mesh->mesh_mutex));
2134 sptps_stop(&mesh->sptps);
2137 closesocket(mesh->sock);
2139 if(!mesh->success) {
2140 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2141 meshlink_errno = MESHLINK_EPEER;
2142 pthread_mutex_unlock(&(mesh->mesh_mutex));
2146 pthread_mutex_unlock(&(mesh->mesh_mutex));
2150 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2151 meshlink_errno = MESHLINK_EINVAL;
2152 pthread_mutex_unlock(&(mesh->mesh_mutex));
2156 char *meshlink_export(meshlink_handle_t *mesh) {
2158 meshlink_errno = MESHLINK_EINVAL;
2162 pthread_mutex_lock(&(mesh->mesh_mutex));
2164 char filename[PATH_MAX];
2165 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2166 FILE *f = fopen(filename, "r");
2169 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2170 meshlink_errno = MESHLINK_ESTORAGE;
2171 pthread_mutex_unlock(&(mesh->mesh_mutex));
2175 fseek(f, 0, SEEK_END);
2176 int fsize = ftell(f);
2179 size_t len = fsize + 9 + strlen(mesh->self->name);
2180 char *buf = xmalloc(len);
2181 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2183 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2184 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2187 meshlink_errno = MESHLINK_ESTORAGE;
2188 pthread_mutex_unlock(&(mesh->mesh_mutex));
2195 pthread_mutex_unlock(&(mesh->mesh_mutex));
2199 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2200 if(!mesh || !data) {
2201 meshlink_errno = MESHLINK_EINVAL;
2205 pthread_mutex_lock(&(mesh->mesh_mutex));
2207 if(strncmp(data, "Name = ", 7)) {
2208 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2209 meshlink_errno = MESHLINK_EPEER;
2210 pthread_mutex_unlock(&(mesh->mesh_mutex));
2214 char *end = strchr(data + 7, '\n');
2217 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2218 meshlink_errno = MESHLINK_EPEER;
2219 pthread_mutex_unlock(&(mesh->mesh_mutex));
2223 int len = end - (data + 7);
2225 memcpy(name, data + 7, len);
2228 if(!check_id(name)) {
2229 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2230 meshlink_errno = MESHLINK_EPEER;
2231 pthread_mutex_unlock(&(mesh->mesh_mutex));
2235 char filename[PATH_MAX];
2236 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2238 if(!access(filename, F_OK)) {
2239 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2240 meshlink_errno = MESHLINK_EEXIST;
2241 pthread_mutex_unlock(&(mesh->mesh_mutex));
2245 if(errno != ENOENT) {
2246 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2247 meshlink_errno = MESHLINK_ESTORAGE;
2248 pthread_mutex_unlock(&(mesh->mesh_mutex));
2252 FILE *f = fopen(filename, "w");
2255 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2256 meshlink_errno = MESHLINK_ESTORAGE;
2257 pthread_mutex_unlock(&(mesh->mesh_mutex));
2261 fwrite(end + 1, strlen(end + 1), 1, f);
2264 load_all_nodes(mesh);
2266 pthread_mutex_unlock(&(mesh->mesh_mutex));
2270 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2271 if(!mesh || !node) {
2272 meshlink_errno = MESHLINK_EINVAL;
2276 pthread_mutex_lock(&(mesh->mesh_mutex));
2280 n->status.blacklisted = true;
2281 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2283 //Make blacklisting persistent in the config file
2284 append_config_file(mesh, n->name, "blacklisted", "yes");
2286 pthread_mutex_unlock(&(mesh->mesh_mutex));
2290 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2291 if(!mesh || !node) {
2292 meshlink_errno = MESHLINK_EINVAL;
2296 pthread_mutex_lock(&(mesh->mesh_mutex));
2298 node_t *n = (node_t *)node;
2299 n->status.blacklisted = false;
2301 //TODO: remove blacklisted = yes from the config file
2303 pthread_mutex_unlock(&(mesh->mesh_mutex));
2307 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2308 mesh->default_blacklist = blacklist;
2311 /* Hint that a hostname may be found at an address
2312 * See header file for detailed comment.
2314 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2315 if(!mesh || !node || !addr) {
2319 // Ignore hints about ourself.
2320 if((node_t *)node == mesh->self) {
2324 pthread_mutex_lock(&(mesh->mesh_mutex));
2326 char *host = NULL, *port = NULL, *str = NULL;
2327 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2330 xasprintf(&str, "%s %s", host, port);
2332 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2333 modify_config_file(mesh, node->name, "Address", str, 5);
2335 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2343 pthread_mutex_unlock(&(mesh->mesh_mutex));
2344 // @TODO do we want to fire off a connection attempt right away?
2347 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2349 node_t *n = utcp->priv;
2350 meshlink_handle_t *mesh = n->mesh;
2351 return mesh->channel_accept_cb;
2354 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2355 meshlink_channel_t *channel = connection->priv;
2361 node_t *n = channel->node;
2362 meshlink_handle_t *mesh = n->mesh;
2364 if(n->status.destroyed) {
2365 meshlink_channel_close(mesh, channel);
2366 } else if(channel->receive_cb) {
2367 channel->receive_cb(mesh, channel, data, len);
2373 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2374 node_t *n = utcp_connection->utcp->priv;
2380 meshlink_handle_t *mesh = n->mesh;
2382 if(!mesh->channel_accept_cb) {
2386 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2388 channel->c = utcp_connection;
2390 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2391 utcp_accept(utcp_connection, channel_recv, channel);
2397 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2398 node_t *n = utcp->priv;
2399 meshlink_handle_t *mesh = n->mesh;
2400 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2403 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2404 if(!mesh || !channel) {
2405 meshlink_errno = MESHLINK_EINVAL;
2409 channel->receive_cb = cb;
2412 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2414 node_t *n = (node_t *)source;
2420 utcp_recv(n->utcp, data, len);
2423 static void channel_poll(struct utcp_connection *connection, size_t len) {
2424 meshlink_channel_t *channel = connection->priv;
2430 node_t *n = channel->node;
2431 meshlink_handle_t *mesh = n->mesh;
2433 if(channel->poll_cb) {
2434 channel->poll_cb(mesh, channel, len);
2438 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2440 channel->poll_cb = cb;
2441 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2444 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2446 meshlink_errno = MESHLINK_EINVAL;
2450 pthread_mutex_lock(&mesh->mesh_mutex);
2451 mesh->channel_accept_cb = cb;
2452 mesh->receive_cb = channel_receive;
2454 for splay_each(node_t, n, mesh->nodes) {
2455 if(!n->utcp && n != mesh->self) {
2456 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2460 pthread_mutex_unlock(&mesh->mesh_mutex);
2463 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) {
2465 abort(); // TODO: handle non-NULL data
2468 if(!mesh || !node) {
2469 meshlink_errno = MESHLINK_EINVAL;
2473 node_t *n = (node_t *)node;
2476 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2477 mesh->receive_cb = channel_receive;
2480 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2485 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2487 channel->receive_cb = cb;
2488 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2491 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2499 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) {
2500 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2503 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2504 if(!mesh || !channel) {
2505 meshlink_errno = MESHLINK_EINVAL;
2509 utcp_shutdown(channel->c, direction);
2512 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2513 if(!mesh || !channel) {
2514 meshlink_errno = MESHLINK_EINVAL;
2518 utcp_close(channel->c);
2522 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2523 if(!mesh || !channel) {
2524 meshlink_errno = MESHLINK_EINVAL;
2533 meshlink_errno = MESHLINK_EINVAL;
2537 // TODO: more finegrained locking.
2538 // Ideally we want to put the data into the UTCP connection's send buffer.
2539 // Then, preferrably only if there is room in the receiver window,
2540 // kick the meshlink thread to go send packets.
2542 pthread_mutex_lock(&mesh->mesh_mutex);
2543 ssize_t retval = utcp_send(channel->c, data, len);
2544 pthread_mutex_unlock(&mesh->mesh_mutex);
2547 meshlink_errno = MESHLINK_ENETWORK;
2553 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2554 if(!mesh || !channel) {
2555 meshlink_errno = MESHLINK_EINVAL;
2559 return channel->c->flags;
2562 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2563 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2564 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2567 if(mesh->node_status_cb) {
2568 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2572 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2574 meshlink_errno = MESHLINK_EINVAL;
2578 pthread_mutex_lock(&mesh->mesh_mutex);
2580 if(mesh->discovery == enable) {
2584 if(mesh->threadstarted) {
2586 discovery_start(mesh);
2588 discovery_stop(mesh);
2592 mesh->discovery = enable;
2595 pthread_mutex_unlock(&mesh->mesh_mutex);
2598 static void __attribute__((constructor)) meshlink_init(void) {
2601 randomize(&seed, sizeof(seed));
2605 static void __attribute__((destructor)) meshlink_exit(void) {
2609 /// Device class traits
2610 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2611 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2612 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2613 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2614 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN