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 {"AddressFamily", VAR_SERVER},
60 {"AutoConnect", VAR_SERVER | VAR_SAFE},
61 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
62 {"BindToInterface", VAR_SERVER},
63 {"Broadcast", VAR_SERVER | VAR_SAFE},
64 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
65 {"DecrementTTL", VAR_SERVER},
66 {"Device", VAR_SERVER},
67 {"DeviceType", VAR_SERVER},
68 {"DirectOnly", VAR_SERVER},
69 {"ECDSAPrivateKeyFile", VAR_SERVER},
70 {"ExperimentalProtocol", VAR_SERVER},
71 {"Forwarding", VAR_SERVER},
72 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
73 {"Hostnames", VAR_SERVER},
74 {"IffOneQueue", VAR_SERVER},
75 {"Interface", VAR_SERVER},
76 {"KeyExpire", VAR_SERVER},
77 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
78 {"LocalDiscovery", VAR_SERVER},
79 {"MACExpire", VAR_SERVER},
80 {"MaxConnectionBurst", VAR_SERVER},
81 {"MaxOutputBufferSize", VAR_SERVER},
82 {"MaxTimeout", VAR_SERVER},
83 {"Mode", VAR_SERVER | VAR_SAFE},
85 {"PingInterval", VAR_SERVER},
86 {"PingTimeout", VAR_SERVER},
87 {"PriorityInheritance", VAR_SERVER},
88 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
89 {"PrivateKeyFile", VAR_SERVER},
90 {"ProcessPriority", VAR_SERVER},
91 {"Proxy", VAR_SERVER},
92 {"ReplayWindow", VAR_SERVER},
93 {"ScriptsExtension", VAR_SERVER},
94 {"ScriptsInterpreter", VAR_SERVER},
95 {"StrictSubnets", VAR_SERVER},
96 {"TunnelServer", VAR_SERVER},
97 {"VDEGroup", VAR_SERVER},
98 {"VDEPort", VAR_SERVER},
99 /* Host configuration */
100 {"Address", VAR_HOST | VAR_MULTIPLE},
101 {"Cipher", VAR_SERVER | VAR_HOST},
102 {"ClampMSS", VAR_SERVER | VAR_HOST},
103 {"Compression", VAR_SERVER | VAR_HOST},
104 {"Digest", VAR_SERVER | VAR_HOST},
105 {"ECDSAPublicKey", VAR_HOST},
106 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
107 {"IndirectData", VAR_SERVER | VAR_HOST},
108 {"MACLength", VAR_SERVER | VAR_HOST},
109 {"PMTU", VAR_SERVER | VAR_HOST},
110 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
112 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
113 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
114 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
115 {"TCPOnly", VAR_SERVER | VAR_HOST},
116 {"Weight", VAR_HOST | VAR_SAFE},
120 static bool fcopy(FILE *out, const char *filename) {
121 FILE *in = fopen(filename, "r");
124 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
131 while((len = fread(buf, 1, sizeof(buf), in))) {
132 fwrite(buf, len, 1, out);
139 static int rstrip(char *value) {
140 int len = strlen(value);
142 while(len && strchr("\t\r\n ", value[len - 1])) {
149 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
152 if(!filename || (*hostname && *port)) {
156 FILE *f = fopen(filename, "r");
162 while(fgets(line, sizeof(line), f)) {
168 p += strcspn(p, "\t =");
174 q = p + strspn(p, "\t ");
177 q += 1 + strspn(q + 1, "\t ");
181 p = q + strcspn(q, "\t ");
187 p += strspn(p, "\t ");
188 p[strcspn(p, "\t ")] = 0;
190 if(!*port && !strcasecmp(line, "Port")) {
192 } else if(!*hostname && !strcasecmp(line, "Address")) {
193 *hostname = xstrdup(q);
201 if(*hostname && *port) {
209 static bool is_valid_hostname(const char *hostname) {
210 for(const char *p = hostname; *p; p++) {
211 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
219 static void set_timeout(int sock, int timeout) {
224 tv.tv_sec = timeout / 1000;
225 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
227 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
228 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
231 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
232 char *hostname = NULL;
234 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
235 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
236 struct addrinfo *aip = ai;
237 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
241 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
244 set_timeout(s, 5000);
246 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
253 send(s, request, sizeof(request) - 1, 0);
254 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
259 if(line[len - 1] == '\n') {
263 char *p = strrchr(line, '\n');
266 hostname = xstrdup(p + 1);
285 // Check that the hostname is reasonable
286 if(hostname && !is_valid_hostname(hostname)) {
292 meshlink_errno = MESHLINK_ERESOLV;
298 static char *get_my_hostname(meshlink_handle_t *mesh) {
299 char *hostname = NULL;
301 char *hostport = NULL;
302 char *name = mesh->self->name;
303 char filename[PATH_MAX] = "";
306 // Use first Address statement in own host config file
307 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
308 scan_for_hostname(filename, &hostname, &port);
314 hostname = meshlink_get_external_address(mesh);
320 f = fopen(filename, "a");
323 fprintf(f, "\nAddress = %s\n", hostname);
326 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
332 if(strchr(hostname, ':')) {
333 xasprintf(&hostport, "[%s]:%s", hostname, port);
335 xasprintf(&hostport, "%s:%s", hostname, port);
338 if(strchr(hostname, ':')) {
339 xasprintf(&hostport, "[%s]", hostname);
341 hostport = xstrdup(hostname);
350 static char *get_line(const char **data) {
351 if(!data || !*data) {
360 static char line[1024];
361 const char *end = strchr(*data, '\n');
362 size_t len = end ? (size_t)(end - *data) : strlen(*data);
364 if(len >= sizeof(line)) {
365 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
369 if(len && !isprint(**data)) {
373 memcpy(line, *data, len);
385 static char *get_value(const char *data, const char *var) {
386 char *line = get_line(&data);
392 char *sep = line + strcspn(line, " \t=");
393 char *val = sep + strspn(sep, " \t");
396 val += 1 + strspn(val + 1, " \t");
401 if(strcasecmp(line, var)) {
408 static bool try_bind(int port) {
409 struct addrinfo *ai = NULL;
410 struct addrinfo hint = {
411 .ai_flags = AI_PASSIVE,
412 .ai_family = AF_UNSPEC,
413 .ai_socktype = SOCK_STREAM,
414 .ai_protocol = IPPROTO_TCP,
418 snprintf(portstr, sizeof(portstr), "%d", port);
420 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
425 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
432 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
447 static int check_port(meshlink_handle_t *mesh) {
448 for(int i = 0; i < 1000; i++) {
449 int port = 0x1000 + (rand() & 0x7fff);
452 char filename[PATH_MAX];
453 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
454 FILE *f = fopen(filename, "a");
457 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
461 fprintf(f, "Port = %d\n", port);
467 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
471 static bool finalize_join(meshlink_handle_t *mesh) {
472 char *name = xstrdup(get_value(mesh->data, "Name"));
475 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
479 if(!check_id(name)) {
480 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
484 char filename[PATH_MAX];
485 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
487 FILE *f = fopen(filename, "w");
490 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
494 fprintf(f, "Name = %s\n", name);
496 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
497 FILE *fh = fopen(filename, "w");
500 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
505 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
506 // Other chunks go unfiltered to their respective host config files
507 const char *p = mesh->data;
510 while((l = get_line(&p))) {
516 // Split line into variable and value
517 int len = strcspn(l, "\t =");
519 value += strspn(value, "\t ");
523 value += strspn(value, "\t ");
529 if(!strcasecmp(l, "Name"))
530 if(strcmp(value, name)) {
534 } else if(!strcasecmp(l, "NetName")) {
538 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
542 for(i = 0; variables[i].name; i++) {
543 if(strcasecmp(l, variables[i].name)) {
551 // Ignore unknown and unsafe variables
553 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
555 } else if(!(variables[i].type & VAR_SAFE)) {
556 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
560 // Copy the safe variable to the right config file
561 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
566 while(l && !strcasecmp(l, "Name")) {
567 if(!check_id(value)) {
568 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
572 if(!strcmp(value, name)) {
573 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
577 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
578 f = fopen(filename, "w");
581 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
585 while((l = get_line(&p))) {
586 if(!strcmp(l, "#---------------------------------------------------------------#")) {
590 int len = strcspn(l, "\t =");
592 if(len == 4 && !strncasecmp(l, "Name", 4)) {
594 value += strspn(value, "\t ");
598 value += strspn(value, "\t ");
612 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
619 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
620 fprintf(fh, "Port = %s\n", mesh->myport);
624 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
627 free(mesh->self->name);
628 free(mesh->self->connection->name);
629 mesh->self->name = xstrdup(name);
630 mesh->self->connection->name = name;
632 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
634 load_all_nodes(mesh);
639 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
641 meshlink_handle_t *mesh = handle;
644 int result = send(mesh->sock, data, len, 0);
646 if(result == -1 && errno == EINTR) {
648 } else if(result <= 0) {
659 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
660 meshlink_handle_t *mesh = handle;
663 case SPTPS_HANDSHAKE:
664 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
667 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
668 memcpy(mesh->data + mesh->thedatalen, msg, len);
669 mesh->thedatalen += len;
670 mesh->data[mesh->thedatalen] = 0;
674 mesh->thedatalen = 0;
675 return finalize_join(mesh);
678 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
679 shutdown(mesh->sock, SHUT_RDWR);
680 mesh->success = true;
690 static bool recvline(meshlink_handle_t *mesh, size_t len) {
691 char *newline = NULL;
697 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
698 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
700 if(result == -1 && errno == EINTR) {
702 } else if(result <= 0) {
706 mesh->blen += result;
709 if((size_t)(newline - mesh->buffer) >= len) {
713 len = newline - mesh->buffer;
715 memcpy(mesh->line, mesh->buffer, len);
717 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
718 mesh->blen -= len + 1;
722 static bool sendline(int fd, char *format, ...) {
723 static char buffer[4096];
728 va_start(ap, format);
729 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
732 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
740 int result = send(fd, p, blen, MSG_NOSIGNAL);
742 if(result == -1 && errno == EINTR) {
744 } else if(result <= 0) {
755 static const char *errstr[] = {
756 [MESHLINK_OK] = "No error",
757 [MESHLINK_EINVAL] = "Invalid argument",
758 [MESHLINK_ENOMEM] = "Out of memory",
759 [MESHLINK_ENOENT] = "No such node",
760 [MESHLINK_EEXIST] = "Node already exists",
761 [MESHLINK_EINTERNAL] = "Internal error",
762 [MESHLINK_ERESOLV] = "Could not resolve hostname",
763 [MESHLINK_ESTORAGE] = "Storage error",
764 [MESHLINK_ENETWORK] = "Network error",
765 [MESHLINK_EPEER] = "Error communicating with peer",
768 const char *meshlink_strerror(meshlink_errno_t err) {
769 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
770 return "Invalid error code";
776 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
779 char pubname[PATH_MAX], privname[PATH_MAX];
781 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
783 if(!(key = ecdsa_generate())) {
784 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
785 meshlink_errno = MESHLINK_EINTERNAL;
788 logger(mesh, MESHLINK_DEBUG, "Done.\n");
791 snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase);
792 f = fopen(privname, "wb");
795 meshlink_errno = MESHLINK_ESTORAGE;
800 fchmod(fileno(f), 0600);
803 if(!ecdsa_write_pem_private_key(key, f)) {
804 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
807 meshlink_errno = MESHLINK_EINTERNAL;
813 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
814 f = fopen(pubname, "a");
817 meshlink_errno = MESHLINK_ESTORAGE;
821 char *pubkey = ecdsa_get_base64_public_key(key);
822 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
831 static struct timeval idle(event_loop_t *loop, void *data) {
833 meshlink_handle_t *mesh = data;
834 struct timeval t, tmin = {3600, 0};
836 for splay_each(node_t, n, mesh->nodes) {
841 t = utcp_timeout(n->utcp);
843 if(timercmp(&t, &tmin, <)) {
851 // Find out what local address a socket would use if we connect to the given address.
852 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
853 // of both endpoints, but this will actually not send any UDP packet.
854 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
855 struct addrinfo *rai = NULL;
856 const struct addrinfo hint = {
857 .ai_family = AF_UNSPEC,
858 .ai_socktype = SOCK_DGRAM,
859 .ai_protocol = IPPROTO_UDP,
862 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
866 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
873 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
880 struct sockaddr_storage sn;
881 socklen_t sl = sizeof(sn);
883 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
887 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
894 // Get our local address(es) by simulating connecting to an Internet host.
895 static void add_local_addresses(meshlink_handle_t *mesh) {
896 char host[NI_MAXHOST];
897 char entry[MAX_STRING_SIZE];
901 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
902 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
903 append_config_file(mesh, mesh->name, "Address", entry);
908 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
909 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
910 append_config_file(mesh, mesh->name, "Address", entry);
914 static bool meshlink_setup(meshlink_handle_t *mesh) {
915 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
916 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
917 meshlink_errno = MESHLINK_ESTORAGE;
921 char filename[PATH_MAX];
922 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
924 if(mkdir(filename, 0777) && errno != EEXIST) {
925 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
926 meshlink_errno = MESHLINK_ESTORAGE;
930 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
932 if(!access(filename, F_OK)) {
933 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
934 meshlink_errno = MESHLINK_EEXIST;
938 FILE *f = fopen(filename, "w");
941 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
942 meshlink_errno = MESHLINK_ESTORAGE;
946 fprintf(f, "Name = %s\n", mesh->name);
949 if(!ecdsa_keygen(mesh)) {
950 meshlink_errno = MESHLINK_EINTERNAL;
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;
1003 mesh->name = xstrdup(name);
1007 pthread_mutexattr_t attr;
1008 pthread_mutexattr_init(&attr);
1009 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1010 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1012 mesh->threadstarted = false;
1013 event_loop_init(&mesh->loop);
1014 mesh->loop.data = mesh;
1016 meshlink_queue_init(&mesh->outpacketqueue);
1018 // Check whether meshlink.conf already exists
1020 char filename[PATH_MAX];
1021 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1023 if(access(filename, R_OK)) {
1024 if(errno == ENOENT) {
1025 // If not, create it
1026 if(!meshlink_setup(mesh)) {
1027 // meshlink_errno is set by meshlink_setup()
1031 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1032 meshlink_close(mesh);
1033 meshlink_errno = MESHLINK_ESTORAGE;
1038 // Read the configuration
1040 init_configuration(&mesh->config);
1042 if(!read_server_config(mesh)) {
1043 meshlink_close(mesh);
1044 meshlink_errno = MESHLINK_ESTORAGE;
1049 struct WSAData wsa_state;
1051 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1055 // Setup up everything
1056 // TODO: we should not open listening sockets yet
1058 if(!setup_network(mesh)) {
1059 meshlink_close(mesh);
1060 meshlink_errno = MESHLINK_ENETWORK;
1064 add_local_addresses(mesh);
1066 idle_set(&mesh->loop, idle, mesh);
1068 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1072 static void *meshlink_main_loop(void *arg) {
1073 meshlink_handle_t *mesh = arg;
1075 pthread_mutex_lock(&(mesh->mesh_mutex));
1077 try_outgoing_connections(mesh);
1079 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1081 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1083 pthread_mutex_unlock(&(mesh->mesh_mutex));
1087 bool meshlink_start(meshlink_handle_t *mesh) {
1089 meshlink_errno = MESHLINK_EINVAL;
1093 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1095 pthread_mutex_lock(&(mesh->mesh_mutex));
1097 if(mesh->threadstarted) {
1098 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1099 pthread_mutex_unlock(&(mesh->mesh_mutex));
1103 if(mesh->listen_socket[0].tcp.fd < 0) {
1104 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1105 meshlink_errno = MESHLINK_ENETWORK;
1109 mesh->thedatalen = 0;
1111 // TODO: open listening sockets first
1113 //Check that a valid name is set
1115 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1116 meshlink_errno = MESHLINK_EINVAL;
1117 pthread_mutex_unlock(&(mesh->mesh_mutex));
1121 // Start the main thread
1123 event_loop_start(&mesh->loop);
1125 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1126 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1127 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1128 meshlink_errno = MESHLINK_EINTERNAL;
1129 pthread_mutex_unlock(&(mesh->mesh_mutex));
1133 mesh->threadstarted = true;
1135 if(mesh->discovery) {
1136 discovery_start(mesh);
1139 pthread_mutex_unlock(&(mesh->mesh_mutex));
1143 void meshlink_stop(meshlink_handle_t *mesh) {
1145 meshlink_errno = MESHLINK_EINVAL;
1149 pthread_mutex_lock(&(mesh->mesh_mutex));
1150 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1153 if(mesh->discovery) {
1154 discovery_stop(mesh);
1157 // Shut down the main thread
1158 event_loop_stop(&mesh->loop);
1160 // Send ourselves a UDP packet to kick the event loop
1161 listen_socket_t *s = &mesh->listen_socket[0];
1163 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1) {
1164 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1167 // Wait for the main thread to finish
1168 pthread_mutex_unlock(&(mesh->mesh_mutex));
1169 pthread_join(mesh->thread, NULL);
1170 pthread_mutex_lock(&(mesh->mesh_mutex));
1172 mesh->threadstarted = false;
1174 // Close all metaconnections
1175 if(mesh->connections) {
1176 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1178 connection_t *c = node->data;
1180 terminate_connection(mesh, c, false);
1184 if(mesh->outgoings) {
1185 list_delete_list(mesh->outgoings);
1188 mesh->outgoings = NULL;
1190 pthread_mutex_unlock(&(mesh->mesh_mutex));
1193 void meshlink_close(meshlink_handle_t *mesh) {
1194 if(!mesh || !mesh->confbase) {
1195 meshlink_errno = MESHLINK_EINVAL;
1199 // stop can be called even if mesh has not been started
1200 meshlink_stop(mesh);
1202 // lock is not released after this
1203 pthread_mutex_lock(&(mesh->mesh_mutex));
1205 // Close and free all resources used.
1207 close_network_connections(mesh);
1209 logger(mesh, MESHLINK_INFO, "Terminating");
1211 exit_configuration(&mesh->config);
1212 event_loop_exit(&mesh->loop);
1216 if(mesh->confbase) {
1222 ecdsa_free(mesh->invitation_key);
1225 free(mesh->appname);
1226 free(mesh->confbase);
1227 pthread_mutex_destroy(&(mesh->mesh_mutex));
1229 memset(mesh, 0, sizeof(*mesh));
1234 static void deltree(const char *dirname) {
1235 DIR *d = opendir(dirname);
1240 while((ent = readdir(d))) {
1241 if(ent->d_name[0] == '.') {
1245 char filename[PATH_MAX];
1246 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1248 if(unlink(filename)) {
1260 bool meshlink_destroy(const char *confbase) {
1262 meshlink_errno = MESHLINK_EINVAL;
1266 char filename[PATH_MAX];
1267 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1269 if(unlink(filename)) {
1270 if(errno == ENOENT) {
1271 meshlink_errno = MESHLINK_ENOENT;
1274 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1275 meshlink_errno = MESHLINK_ESTORAGE;
1285 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1287 meshlink_errno = MESHLINK_EINVAL;
1291 pthread_mutex_lock(&(mesh->mesh_mutex));
1292 mesh->receive_cb = cb;
1293 pthread_mutex_unlock(&(mesh->mesh_mutex));
1296 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1298 meshlink_errno = MESHLINK_EINVAL;
1302 pthread_mutex_lock(&(mesh->mesh_mutex));
1303 mesh->node_status_cb = cb;
1304 pthread_mutex_unlock(&(mesh->mesh_mutex));
1307 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1309 pthread_mutex_lock(&(mesh->mesh_mutex));
1311 mesh->log_level = cb ? level : 0;
1312 pthread_mutex_unlock(&(mesh->mesh_mutex));
1315 global_log_level = cb ? level : 0;
1319 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1320 meshlink_packethdr_t *hdr;
1322 // Validate arguments
1323 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1324 meshlink_errno = MESHLINK_EINVAL;
1333 meshlink_errno = MESHLINK_EINVAL;
1337 // Prepare the packet
1338 vpn_packet_t *packet = malloc(sizeof(*packet));
1341 meshlink_errno = MESHLINK_ENOMEM;
1345 packet->probe = false;
1346 packet->tcp = false;
1347 packet->len = len + sizeof(*hdr);
1349 hdr = (meshlink_packethdr_t *)packet->data;
1350 memset(hdr, 0, sizeof(*hdr));
1351 // leave the last byte as 0 to make sure strings are always
1352 // null-terminated if they are longer than the buffer
1353 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1354 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1356 memcpy(packet->data + sizeof(*hdr), data, len);
1359 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1361 meshlink_errno = MESHLINK_ENOMEM;
1365 // Notify event loop
1366 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1371 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1373 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1379 mesh->self->in_packets++;
1380 mesh->self->in_bytes += packet->len;
1381 route(mesh, mesh->self, packet);
1384 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1385 if(!mesh || !destination) {
1386 meshlink_errno = MESHLINK_EINVAL;
1390 pthread_mutex_lock(&(mesh->mesh_mutex));
1392 node_t *n = (node_t *)destination;
1394 if(!n->status.reachable) {
1395 pthread_mutex_unlock(&(mesh->mesh_mutex));
1398 } else if(n->mtuprobes > 30 && n->minmtu) {
1399 pthread_mutex_unlock(&(mesh->mesh_mutex));
1402 pthread_mutex_unlock(&(mesh->mesh_mutex));
1407 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1408 if(!mesh || !node) {
1409 meshlink_errno = MESHLINK_EINVAL;
1413 pthread_mutex_lock(&(mesh->mesh_mutex));
1415 node_t *n = (node_t *)node;
1417 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1418 meshlink_errno = MESHLINK_EINTERNAL;
1419 pthread_mutex_unlock(&(mesh->mesh_mutex));
1423 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1426 meshlink_errno = MESHLINK_EINTERNAL;
1429 pthread_mutex_unlock(&(mesh->mesh_mutex));
1433 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1435 meshlink_errno = MESHLINK_EINVAL;
1439 return (meshlink_node_t *)mesh->self;
1442 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1443 if(!mesh || !name) {
1444 meshlink_errno = MESHLINK_EINVAL;
1448 meshlink_node_t *node = NULL;
1450 pthread_mutex_lock(&(mesh->mesh_mutex));
1451 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1452 pthread_mutex_unlock(&(mesh->mesh_mutex));
1456 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1457 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1458 meshlink_errno = MESHLINK_EINVAL;
1462 meshlink_node_t **result;
1465 pthread_mutex_lock(&(mesh->mesh_mutex));
1467 *nmemb = mesh->nodes->count;
1468 result = realloc(nodes, *nmemb * sizeof(*nodes));
1471 meshlink_node_t **p = result;
1473 for splay_each(node_t, n, mesh->nodes) {
1474 *p++ = (meshlink_node_t *)n;
1479 meshlink_errno = MESHLINK_ENOMEM;
1482 pthread_mutex_unlock(&(mesh->mesh_mutex));
1487 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1488 if(!mesh || !data || !len || !signature || !siglen) {
1489 meshlink_errno = MESHLINK_EINVAL;
1493 if(*siglen < MESHLINK_SIGLEN) {
1494 meshlink_errno = MESHLINK_EINVAL;
1498 pthread_mutex_lock(&(mesh->mesh_mutex));
1500 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1501 meshlink_errno = MESHLINK_EINTERNAL;
1502 pthread_mutex_unlock(&(mesh->mesh_mutex));
1506 *siglen = MESHLINK_SIGLEN;
1507 pthread_mutex_unlock(&(mesh->mesh_mutex));
1511 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1512 if(!mesh || !data || !len || !signature) {
1513 meshlink_errno = MESHLINK_EINVAL;
1517 if(siglen != MESHLINK_SIGLEN) {
1518 meshlink_errno = MESHLINK_EINVAL;
1522 pthread_mutex_lock(&(mesh->mesh_mutex));
1526 struct node_t *n = (struct node_t *)source;
1527 node_read_ecdsa_public_key(mesh, n);
1530 meshlink_errno = MESHLINK_EINTERNAL;
1533 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1536 pthread_mutex_unlock(&(mesh->mesh_mutex));
1540 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1541 char filename[PATH_MAX];
1543 pthread_mutex_lock(&(mesh->mesh_mutex));
1545 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1547 if(mkdir(filename, 0700) && errno != EEXIST) {
1548 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1549 meshlink_errno = MESHLINK_ESTORAGE;
1550 pthread_mutex_unlock(&(mesh->mesh_mutex));
1554 // Count the number of valid invitations, clean up old ones
1555 DIR *dir = opendir(filename);
1558 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1559 meshlink_errno = MESHLINK_ESTORAGE;
1560 pthread_mutex_unlock(&(mesh->mesh_mutex));
1567 time_t deadline = time(NULL) - 604800; // 1 week in the past
1569 while((ent = readdir(dir))) {
1570 if(strlen(ent->d_name) != 24) {
1574 char invname[PATH_MAX];
1576 snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name);
1578 if(!stat(invname, &st)) {
1579 if(mesh->invitation_key && deadline < st.st_mtime) {
1585 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1591 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1593 meshlink_errno = MESHLINK_ESTORAGE;
1594 pthread_mutex_unlock(&(mesh->mesh_mutex));
1600 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1602 // Remove the key if there are no outstanding invitations.
1606 if(mesh->invitation_key) {
1607 ecdsa_free(mesh->invitation_key);
1608 mesh->invitation_key = NULL;
1612 if(mesh->invitation_key) {
1613 pthread_mutex_unlock(&(mesh->mesh_mutex));
1617 // Create a new key if necessary.
1618 FILE *f = fopen(filename, "rb");
1621 if(errno != ENOENT) {
1622 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1623 meshlink_errno = MESHLINK_ESTORAGE;
1624 pthread_mutex_unlock(&(mesh->mesh_mutex));
1628 mesh->invitation_key = ecdsa_generate();
1630 if(!mesh->invitation_key) {
1631 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1632 meshlink_errno = MESHLINK_EINTERNAL;
1633 pthread_mutex_unlock(&(mesh->mesh_mutex));
1637 f = fopen(filename, "wb");
1640 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1641 meshlink_errno = MESHLINK_ESTORAGE;
1642 pthread_mutex_unlock(&(mesh->mesh_mutex));
1646 chmod(filename, 0600);
1647 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1650 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1653 if(!mesh->invitation_key) {
1654 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1655 meshlink_errno = MESHLINK_ESTORAGE;
1659 pthread_mutex_unlock(&(mesh->mesh_mutex));
1660 return mesh->invitation_key;
1663 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1664 if(!mesh || !address) {
1665 meshlink_errno = MESHLINK_EINVAL;
1669 if(!is_valid_hostname(address)) {
1670 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1671 meshlink_errno = MESHLINK_EINVAL;
1677 pthread_mutex_lock(&(mesh->mesh_mutex));
1678 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1679 pthread_mutex_unlock(&(mesh->mesh_mutex));
1684 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1686 meshlink_errno = MESHLINK_EINVAL;
1690 char *address = meshlink_get_external_address(mesh);
1698 pthread_mutex_lock(&(mesh->mesh_mutex));
1699 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1700 pthread_mutex_unlock(&(mesh->mesh_mutex));
1706 int meshlink_get_port(meshlink_handle_t *mesh) {
1708 meshlink_errno = MESHLINK_EINVAL;
1713 meshlink_errno = MESHLINK_EINTERNAL;
1717 return atoi(mesh->myport);
1720 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1721 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1722 meshlink_errno = MESHLINK_EINVAL;
1726 if(mesh->myport && port == atoi(mesh->myport)) {
1730 if(!try_bind(port)) {
1731 meshlink_errno = MESHLINK_ENETWORK;
1737 pthread_mutex_lock(&(mesh->mesh_mutex));
1739 if(mesh->threadstarted) {
1740 meshlink_errno = MESHLINK_EINVAL;
1744 close_network_connections(mesh);
1745 exit_configuration(&mesh->config);
1748 snprintf(portstr, sizeof(portstr), "%d", port);
1749 portstr[sizeof(portstr) - 1] = 0;
1751 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1753 init_configuration(&mesh->config);
1755 if(!read_server_config(mesh)) {
1756 meshlink_errno = MESHLINK_ESTORAGE;
1757 } else if(!setup_network(mesh)) {
1758 meshlink_errno = MESHLINK_ENETWORK;
1764 pthread_mutex_unlock(&(mesh->mesh_mutex));
1769 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1771 meshlink_errno = MESHLINK_EINVAL;
1775 pthread_mutex_lock(&(mesh->mesh_mutex));
1777 // Check validity of the new node's name
1778 if(!check_id(name)) {
1779 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1780 meshlink_errno = MESHLINK_EINVAL;
1781 pthread_mutex_unlock(&(mesh->mesh_mutex));
1785 // Ensure no host configuration file with that name exists
1786 char filename[PATH_MAX];
1787 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1789 if(!access(filename, F_OK)) {
1790 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1791 meshlink_errno = MESHLINK_EEXIST;
1792 pthread_mutex_unlock(&(mesh->mesh_mutex));
1796 // Ensure no other nodes know about this name
1797 if(meshlink_get_node(mesh, name)) {
1798 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1799 meshlink_errno = MESHLINK_EEXIST;
1800 pthread_mutex_unlock(&(mesh->mesh_mutex));
1804 // Get the local address
1805 char *address = get_my_hostname(mesh);
1808 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1809 meshlink_errno = MESHLINK_ERESOLV;
1810 pthread_mutex_unlock(&(mesh->mesh_mutex));
1814 if(!refresh_invitation_key(mesh)) {
1815 meshlink_errno = MESHLINK_EINTERNAL;
1816 pthread_mutex_unlock(&(mesh->mesh_mutex));
1822 // Create a hash of the key.
1823 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1824 sha512(fingerprint, strlen(fingerprint), hash);
1825 b64encode_urlsafe(hash, hash, 18);
1827 // Create a random cookie for this invitation.
1829 randomize(cookie, 18);
1831 // Create a filename that doesn't reveal the cookie itself
1832 char buf[18 + strlen(fingerprint)];
1833 char cookiehash[64];
1834 memcpy(buf, cookie, 18);
1835 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1836 sha512(buf, sizeof(buf), cookiehash);
1837 b64encode_urlsafe(cookiehash, cookiehash, 18);
1839 b64encode_urlsafe(cookie, cookie, 18);
1843 // Create a file containing the details of the invitation.
1844 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1845 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1848 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1849 meshlink_errno = MESHLINK_ESTORAGE;
1850 pthread_mutex_unlock(&(mesh->mesh_mutex));
1854 FILE *f = fdopen(ifd, "w");
1860 // Fill in the details.
1861 fprintf(f, "Name = %s\n", name);
1863 // fprintf(f, "NetName = %s\n", netname);
1864 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1866 // Copy Broadcast and Mode
1867 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1868 FILE *tc = fopen(filename, "r");
1873 while(fgets(buf, sizeof(buf), tc)) {
1874 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1875 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1878 // Make sure there is a newline character.
1879 if(!strchr(buf, '\n')) {
1887 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1888 meshlink_errno = MESHLINK_ESTORAGE;
1889 pthread_mutex_unlock(&(mesh->mesh_mutex));
1893 fprintf(f, "#---------------------------------------------------------------#\n");
1894 fprintf(f, "Name = %s\n", mesh->self->name);
1896 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1900 // Create an URL from the local address, key hash and cookie
1902 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1905 pthread_mutex_unlock(&(mesh->mesh_mutex));
1909 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1910 if(!mesh || !invitation) {
1911 meshlink_errno = MESHLINK_EINVAL;
1915 pthread_mutex_lock(&(mesh->mesh_mutex));
1917 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1918 char copy[strlen(invitation) + 1];
1919 strcpy(copy, invitation);
1921 // Split the invitation URL into hostname, port, key hash and cookie.
1923 char *slash = strchr(copy, '/');
1931 if(strlen(slash) != 48) {
1935 char *address = copy;
1938 if(*address == '[') {
1940 char *bracket = strchr(address, ']');
1948 if(bracket[1] == ':') {
1952 port = strchr(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);
1978 //Before doing meshlink_join make sure we are not connected to another mesh
1979 if(mesh->threadstarted) {
1983 // Connect to the meshlink daemon mentioned in the URL.
1984 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1987 meshlink_errno = MESHLINK_ERESOLV;
1988 pthread_mutex_unlock(&(mesh->mesh_mutex));
1992 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1994 if(mesh->sock <= 0) {
1995 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1997 meshlink_errno = MESHLINK_ENETWORK;
1998 pthread_mutex_unlock(&(mesh->mesh_mutex));
2002 set_timeout(mesh->sock, 5000);
2004 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
2005 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2006 closesocket(mesh->sock);
2008 meshlink_errno = MESHLINK_ENETWORK;
2009 pthread_mutex_unlock(&(mesh->mesh_mutex));
2015 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2017 // Tell him we have an invitation, and give him our throw-away key.
2021 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2022 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2023 closesocket(mesh->sock);
2024 meshlink_errno = MESHLINK_ENETWORK;
2025 pthread_mutex_unlock(&(mesh->mesh_mutex));
2031 char hisname[4096] = "";
2032 int code, hismajor, hisminor = 0;
2034 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) {
2035 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2036 closesocket(mesh->sock);
2037 meshlink_errno = MESHLINK_ENETWORK;
2038 pthread_mutex_unlock(&(mesh->mesh_mutex));
2042 // Check if the hash of the key he gave us matches the hash in the URL.
2043 char *fingerprint = mesh->line + 2;
2046 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2047 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2048 meshlink_errno = MESHLINK_EINTERNAL;
2049 pthread_mutex_unlock(&(mesh->mesh_mutex));
2053 if(memcmp(hishash, mesh->hash, 18)) {
2054 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2055 meshlink_errno = MESHLINK_EPEER;
2056 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2064 meshlink_errno = MESHLINK_EINTERNAL;
2065 pthread_mutex_unlock(&(mesh->mesh_mutex));
2069 // Start an SPTPS session
2070 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2071 meshlink_errno = MESHLINK_EINTERNAL;
2072 pthread_mutex_unlock(&(mesh->mesh_mutex));
2076 // Feed rest of input buffer to SPTPS
2077 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2078 meshlink_errno = MESHLINK_EPEER;
2079 pthread_mutex_unlock(&(mesh->mesh_mutex));
2085 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2087 if(errno == EINTR) {
2091 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2092 meshlink_errno = MESHLINK_ENETWORK;
2093 pthread_mutex_unlock(&(mesh->mesh_mutex));
2097 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2098 meshlink_errno = MESHLINK_EPEER;
2099 pthread_mutex_unlock(&(mesh->mesh_mutex));
2104 sptps_stop(&mesh->sptps);
2107 closesocket(mesh->sock);
2109 if(!mesh->success) {
2110 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2111 meshlink_errno = MESHLINK_EPEER;
2112 pthread_mutex_unlock(&(mesh->mesh_mutex));
2116 pthread_mutex_unlock(&(mesh->mesh_mutex));
2120 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
2121 meshlink_errno = MESHLINK_EINVAL;
2122 pthread_mutex_unlock(&(mesh->mesh_mutex));
2126 char *meshlink_export(meshlink_handle_t *mesh) {
2128 meshlink_errno = MESHLINK_EINVAL;
2132 pthread_mutex_lock(&(mesh->mesh_mutex));
2134 char filename[PATH_MAX];
2135 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2136 FILE *f = fopen(filename, "r");
2139 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2140 meshlink_errno = MESHLINK_ESTORAGE;
2141 pthread_mutex_unlock(&(mesh->mesh_mutex));
2145 fseek(f, 0, SEEK_END);
2146 int fsize = ftell(f);
2149 size_t len = fsize + 9 + strlen(mesh->self->name);
2150 char *buf = xmalloc(len);
2151 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2153 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2154 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2157 meshlink_errno = MESHLINK_ESTORAGE;
2158 pthread_mutex_unlock(&(mesh->mesh_mutex));
2165 pthread_mutex_unlock(&(mesh->mesh_mutex));
2169 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2170 if(!mesh || !data) {
2171 meshlink_errno = MESHLINK_EINVAL;
2175 pthread_mutex_lock(&(mesh->mesh_mutex));
2177 if(strncmp(data, "Name = ", 7)) {
2178 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2179 meshlink_errno = MESHLINK_EPEER;
2180 pthread_mutex_unlock(&(mesh->mesh_mutex));
2184 char *end = strchr(data + 7, '\n');
2187 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2188 meshlink_errno = MESHLINK_EPEER;
2189 pthread_mutex_unlock(&(mesh->mesh_mutex));
2193 int len = end - (data + 7);
2195 memcpy(name, data + 7, len);
2198 if(!check_id(name)) {
2199 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2200 meshlink_errno = MESHLINK_EPEER;
2201 pthread_mutex_unlock(&(mesh->mesh_mutex));
2205 char filename[PATH_MAX];
2206 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2208 if(!access(filename, F_OK)) {
2209 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2210 meshlink_errno = MESHLINK_EEXIST;
2211 pthread_mutex_unlock(&(mesh->mesh_mutex));
2215 if(errno != ENOENT) {
2216 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2217 meshlink_errno = MESHLINK_ESTORAGE;
2218 pthread_mutex_unlock(&(mesh->mesh_mutex));
2222 FILE *f = fopen(filename, "w");
2225 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2226 meshlink_errno = MESHLINK_ESTORAGE;
2227 pthread_mutex_unlock(&(mesh->mesh_mutex));
2231 fwrite(end + 1, strlen(end + 1), 1, f);
2234 load_all_nodes(mesh);
2236 pthread_mutex_unlock(&(mesh->mesh_mutex));
2240 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2241 if(!mesh || !node) {
2242 meshlink_errno = MESHLINK_EINVAL;
2246 pthread_mutex_lock(&(mesh->mesh_mutex));
2250 n->status.blacklisted = true;
2251 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2253 //Make blacklisting persistent in the config file
2254 append_config_file(mesh, n->name, "blacklisted", "yes");
2256 pthread_mutex_unlock(&(mesh->mesh_mutex));
2260 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2261 if(!mesh || !node) {
2262 meshlink_errno = MESHLINK_EINVAL;
2266 pthread_mutex_lock(&(mesh->mesh_mutex));
2268 node_t *n = (node_t *)node;
2269 n->status.blacklisted = false;
2271 //TODO: remove blacklisted = yes from the config file
2273 pthread_mutex_unlock(&(mesh->mesh_mutex));
2277 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2278 mesh->default_blacklist = blacklist;
2281 /* Hint that a hostname may be found at an address
2282 * See header file for detailed comment.
2284 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2285 if(!mesh || !node || !addr) {
2289 // Ignore hints about ourself.
2290 if((node_t *)node == mesh->self) {
2294 pthread_mutex_lock(&(mesh->mesh_mutex));
2296 char *host = NULL, *port = NULL, *str = NULL;
2297 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2300 xasprintf(&str, "%s %s", host, port);
2302 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2303 modify_config_file(mesh, node->name, "Address", str, 5);
2305 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2313 pthread_mutex_unlock(&(mesh->mesh_mutex));
2314 // @TODO do we want to fire off a connection attempt right away?
2317 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2319 node_t *n = utcp->priv;
2320 meshlink_handle_t *mesh = n->mesh;
2321 return mesh->channel_accept_cb;
2324 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2325 meshlink_channel_t *channel = connection->priv;
2331 node_t *n = channel->node;
2332 meshlink_handle_t *mesh = n->mesh;
2334 if(n->status.destroyed) {
2335 meshlink_channel_close(mesh, channel);
2336 } else if(channel->receive_cb) {
2337 channel->receive_cb(mesh, channel, data, len);
2343 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2344 node_t *n = utcp_connection->utcp->priv;
2350 meshlink_handle_t *mesh = n->mesh;
2352 if(!mesh->channel_accept_cb) {
2356 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2358 channel->c = utcp_connection;
2360 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2361 utcp_accept(utcp_connection, channel_recv, channel);
2367 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2368 node_t *n = utcp->priv;
2369 meshlink_handle_t *mesh = n->mesh;
2370 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2373 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2374 if(!mesh || !channel) {
2375 meshlink_errno = MESHLINK_EINVAL;
2379 channel->receive_cb = cb;
2382 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2384 node_t *n = (node_t *)source;
2390 utcp_recv(n->utcp, data, len);
2393 static void channel_poll(struct utcp_connection *connection, size_t len) {
2394 meshlink_channel_t *channel = connection->priv;
2400 node_t *n = channel->node;
2401 meshlink_handle_t *mesh = n->mesh;
2403 if(channel->poll_cb) {
2404 channel->poll_cb(mesh, channel, len);
2408 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2410 channel->poll_cb = cb;
2411 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2414 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2416 meshlink_errno = MESHLINK_EINVAL;
2420 pthread_mutex_lock(&mesh->mesh_mutex);
2421 mesh->channel_accept_cb = cb;
2422 mesh->receive_cb = channel_receive;
2424 for splay_each(node_t, n, mesh->nodes) {
2425 if(!n->utcp && n != mesh->self) {
2426 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2430 pthread_mutex_unlock(&mesh->mesh_mutex);
2433 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) {
2435 abort(); // TODO: handle non-NULL data
2438 if(!mesh || !node) {
2439 meshlink_errno = MESHLINK_EINVAL;
2443 node_t *n = (node_t *)node;
2446 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2447 mesh->receive_cb = channel_receive;
2450 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2455 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2457 channel->receive_cb = cb;
2458 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2461 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2469 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) {
2470 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2473 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2474 if(!mesh || !channel) {
2475 meshlink_errno = MESHLINK_EINVAL;
2479 utcp_shutdown(channel->c, direction);
2482 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2483 if(!mesh || !channel) {
2484 meshlink_errno = MESHLINK_EINVAL;
2488 utcp_close(channel->c);
2492 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2493 if(!mesh || !channel) {
2494 meshlink_errno = MESHLINK_EINVAL;
2503 meshlink_errno = MESHLINK_EINVAL;
2507 // TODO: more finegrained locking.
2508 // Ideally we want to put the data into the UTCP connection's send buffer.
2509 // Then, preferrably only if there is room in the receiver window,
2510 // kick the meshlink thread to go send packets.
2512 pthread_mutex_lock(&mesh->mesh_mutex);
2513 ssize_t retval = utcp_send(channel->c, data, len);
2514 pthread_mutex_unlock(&mesh->mesh_mutex);
2517 meshlink_errno = MESHLINK_ENETWORK;
2523 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2524 if(!mesh || !channel) {
2525 meshlink_errno = MESHLINK_EINVAL;
2529 return channel->c->flags;
2532 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2533 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2534 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2537 if(mesh->node_status_cb) {
2538 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2542 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2544 meshlink_errno = MESHLINK_EINVAL;
2548 pthread_mutex_lock(&mesh->mesh_mutex);
2550 if(mesh->discovery == enable) {
2554 if(mesh->threadstarted) {
2556 discovery_start(mesh);
2558 discovery_stop(mesh);
2562 mesh->discovery = enable;
2565 pthread_mutex_unlock(&mesh->mesh_mutex);
2568 static void __attribute__((constructor)) meshlink_init(void) {
2571 randomize(&seed, sizeof(seed));
2575 static void __attribute__((destructor)) meshlink_exit(void) {
2579 /// Device class traits
2580 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2581 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2582 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2583 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2584 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN