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 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 meshlink_errno = MESHLINK_ESTORAGE;
458 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
462 fprintf(f, "Port = %d\n", port);
468 meshlink_errno = MESHLINK_ENETWORK;
469 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
473 static bool finalize_join(meshlink_handle_t *mesh) {
474 char *name = xstrdup(get_value(mesh->data, "Name"));
477 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
481 if(!check_id(name)) {
482 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
486 char filename[PATH_MAX];
487 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
489 FILE *f = fopen(filename, "w");
492 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
496 fprintf(f, "Name = %s\n", name);
498 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
499 FILE *fh = fopen(filename, "w");
502 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
507 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
508 // Other chunks go unfiltered to their respective host config files
509 const char *p = mesh->data;
512 while((l = get_line(&p))) {
518 // Split line into variable and value
519 int len = strcspn(l, "\t =");
521 value += strspn(value, "\t ");
525 value += strspn(value, "\t ");
531 if(!strcasecmp(l, "Name"))
532 if(strcmp(value, name)) {
536 } else if(!strcasecmp(l, "NetName")) {
540 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
544 for(i = 0; variables[i].name; i++) {
545 if(strcasecmp(l, variables[i].name)) {
553 // Ignore unknown and unsafe variables
555 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
557 } else if(!(variables[i].type & VAR_SAFE)) {
558 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
562 // Copy the safe variable to the right config file
563 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
568 while(l && !strcasecmp(l, "Name")) {
569 if(!check_id(value)) {
570 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
574 if(!strcmp(value, name)) {
575 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
579 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
580 f = fopen(filename, "w");
583 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
587 while((l = get_line(&p))) {
588 if(!strcmp(l, "#---------------------------------------------------------------#")) {
592 int len = strcspn(l, "\t =");
594 if(len == 4 && !strncasecmp(l, "Name", 4)) {
596 value += strspn(value, "\t ");
600 value += strspn(value, "\t ");
614 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
621 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
622 fprintf(fh, "Port = %s\n", mesh->myport);
626 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
629 free(mesh->self->name);
630 free(mesh->self->connection->name);
631 mesh->self->name = xstrdup(name);
632 mesh->self->connection->name = name;
634 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
636 load_all_nodes(mesh);
641 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
643 meshlink_handle_t *mesh = handle;
646 int result = send(mesh->sock, data, len, 0);
648 if(result == -1 && errno == EINTR) {
650 } else if(result <= 0) {
661 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
662 meshlink_handle_t *mesh = handle;
665 case SPTPS_HANDSHAKE:
666 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
669 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
670 memcpy(mesh->data + mesh->thedatalen, msg, len);
671 mesh->thedatalen += len;
672 mesh->data[mesh->thedatalen] = 0;
676 mesh->thedatalen = 0;
677 return finalize_join(mesh);
680 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
681 shutdown(mesh->sock, SHUT_RDWR);
682 mesh->success = true;
692 static bool recvline(meshlink_handle_t *mesh, size_t len) {
693 char *newline = NULL;
699 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
700 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
702 if(result == -1 && errno == EINTR) {
704 } else if(result <= 0) {
708 mesh->blen += result;
711 if((size_t)(newline - mesh->buffer) >= len) {
715 len = newline - mesh->buffer;
717 memcpy(mesh->line, mesh->buffer, len);
719 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
720 mesh->blen -= len + 1;
724 static bool sendline(int fd, char *format, ...) {
725 static char buffer[4096];
730 va_start(ap, format);
731 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
734 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
742 int result = send(fd, p, blen, MSG_NOSIGNAL);
744 if(result == -1 && errno == EINTR) {
746 } else if(result <= 0) {
757 static const char *errstr[] = {
758 [MESHLINK_OK] = "No error",
759 [MESHLINK_EINVAL] = "Invalid argument",
760 [MESHLINK_ENOMEM] = "Out of memory",
761 [MESHLINK_ENOENT] = "No such node",
762 [MESHLINK_EEXIST] = "Node already exists",
763 [MESHLINK_EINTERNAL] = "Internal error",
764 [MESHLINK_ERESOLV] = "Could not resolve hostname",
765 [MESHLINK_ESTORAGE] = "Storage error",
766 [MESHLINK_ENETWORK] = "Network error",
767 [MESHLINK_EPEER] = "Error communicating with peer",
770 const char *meshlink_strerror(meshlink_errno_t err) {
771 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
772 return "Invalid error code";
778 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
781 char pubname[PATH_MAX], privname[PATH_MAX];
783 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
785 if(!(key = ecdsa_generate())) {
786 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
787 meshlink_errno = MESHLINK_EINTERNAL;
790 logger(mesh, MESHLINK_DEBUG, "Done.\n");
793 snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase);
794 f = fopen(privname, "wb");
797 meshlink_errno = MESHLINK_ESTORAGE;
802 fchmod(fileno(f), 0600);
805 if(!ecdsa_write_pem_private_key(key, f)) {
806 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
809 meshlink_errno = MESHLINK_EINTERNAL;
815 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
816 f = fopen(pubname, "a");
819 meshlink_errno = MESHLINK_ESTORAGE;
823 char *pubkey = ecdsa_get_base64_public_key(key);
824 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
833 static struct timeval idle(event_loop_t *loop, void *data) {
835 meshlink_handle_t *mesh = data;
836 struct timeval t, tmin = {3600, 0};
838 for splay_each(node_t, n, mesh->nodes) {
843 t = utcp_timeout(n->utcp);
845 if(timercmp(&t, &tmin, <)) {
853 // Find out what local address a socket would use if we connect to the given address.
854 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
855 // of both endpoints, but this will actually not send any UDP packet.
856 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
857 struct addrinfo *rai = NULL;
858 const struct addrinfo hint = {
859 .ai_family = AF_UNSPEC,
860 .ai_socktype = SOCK_DGRAM,
861 .ai_protocol = IPPROTO_UDP,
864 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
868 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
875 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
882 struct sockaddr_storage sn;
883 socklen_t sl = sizeof(sn);
885 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
889 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
896 // Get our local address(es) by simulating connecting to an Internet host.
897 static void add_local_addresses(meshlink_handle_t *mesh) {
898 char host[NI_MAXHOST];
899 char entry[MAX_STRING_SIZE];
903 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
904 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
905 append_config_file(mesh, mesh->name, "Address", entry);
910 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
911 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
912 append_config_file(mesh, mesh->name, "Address", entry);
916 static bool meshlink_setup(meshlink_handle_t *mesh) {
917 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
918 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
919 meshlink_errno = MESHLINK_ESTORAGE;
923 char filename[PATH_MAX];
924 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
926 if(mkdir(filename, 0777) && errno != EEXIST) {
927 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
928 meshlink_errno = MESHLINK_ESTORAGE;
932 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
934 if(!access(filename, F_OK)) {
935 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
936 meshlink_errno = MESHLINK_EEXIST;
940 FILE *f = fopen(filename, "w");
943 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
944 meshlink_errno = MESHLINK_ESTORAGE;
948 fprintf(f, "Name = %s\n", mesh->name);
951 if(!ecdsa_keygen(mesh)) {
952 meshlink_errno = MESHLINK_EINTERNAL;
957 if (check_port(mesh) == 0) {
958 meshlink_errno = MESHLINK_ENETWORK;
966 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
967 // Validate arguments provided by the application
968 bool usingname = false;
970 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
972 if(!confbase || !*confbase) {
973 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
974 meshlink_errno = MESHLINK_EINVAL;
978 if(!appname || !*appname) {
979 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
980 meshlink_errno = MESHLINK_EINVAL;
984 if(!name || !*name) {
985 logger(NULL, MESHLINK_ERROR, "No name given!\n");
987 } else { //check name only if there is a name != NULL
989 if(!check_id(name)) {
990 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
991 meshlink_errno = MESHLINK_EINVAL;
998 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
999 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1000 meshlink_errno = MESHLINK_EINVAL;
1004 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1005 mesh->confbase = xstrdup(confbase);
1006 mesh->appname = xstrdup(appname);
1007 mesh->devclass = devclass;
1010 mesh->name = xstrdup(name);
1014 pthread_mutexattr_t attr;
1015 pthread_mutexattr_init(&attr);
1016 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1017 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1019 mesh->threadstarted = false;
1020 event_loop_init(&mesh->loop);
1021 mesh->loop.data = mesh;
1023 meshlink_queue_init(&mesh->outpacketqueue);
1025 // Check whether meshlink.conf already exists
1027 char filename[PATH_MAX];
1028 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1030 if(access(filename, R_OK)) {
1031 if(errno == ENOENT) {
1032 // If not, create it
1033 if(!meshlink_setup(mesh)) {
1034 // meshlink_errno is set by meshlink_setup()
1038 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1039 meshlink_close(mesh);
1040 meshlink_errno = MESHLINK_ESTORAGE;
1045 // Read the configuration
1047 init_configuration(&mesh->config);
1049 if(!read_server_config(mesh)) {
1050 meshlink_close(mesh);
1051 meshlink_errno = MESHLINK_ESTORAGE;
1056 struct WSAData wsa_state;
1058 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1062 // Setup up everything
1063 // TODO: we should not open listening sockets yet
1065 if(!setup_network(mesh)) {
1066 meshlink_close(mesh);
1067 meshlink_errno = MESHLINK_ENETWORK;
1071 add_local_addresses(mesh);
1073 idle_set(&mesh->loop, idle, mesh);
1075 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1079 static void *meshlink_main_loop(void *arg) {
1080 meshlink_handle_t *mesh = arg;
1082 pthread_mutex_lock(&(mesh->mesh_mutex));
1084 try_outgoing_connections(mesh);
1086 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1088 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1090 pthread_mutex_unlock(&(mesh->mesh_mutex));
1094 bool meshlink_start(meshlink_handle_t *mesh) {
1096 meshlink_errno = MESHLINK_EINVAL;
1100 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1102 pthread_mutex_lock(&(mesh->mesh_mutex));
1104 if(mesh->threadstarted) {
1105 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1106 pthread_mutex_unlock(&(mesh->mesh_mutex));
1110 if(mesh->listen_socket[0].tcp.fd < 0) {
1111 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1112 meshlink_errno = MESHLINK_ENETWORK;
1116 mesh->thedatalen = 0;
1118 // TODO: open listening sockets first
1120 //Check that a valid name is set
1122 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1123 meshlink_errno = MESHLINK_EINVAL;
1124 pthread_mutex_unlock(&(mesh->mesh_mutex));
1128 // Start the main thread
1130 event_loop_start(&mesh->loop);
1132 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1133 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1134 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1135 meshlink_errno = MESHLINK_EINTERNAL;
1136 pthread_mutex_unlock(&(mesh->mesh_mutex));
1140 mesh->threadstarted = true;
1142 if(mesh->discovery) {
1143 discovery_start(mesh);
1146 pthread_mutex_unlock(&(mesh->mesh_mutex));
1150 void meshlink_stop(meshlink_handle_t *mesh) {
1152 meshlink_errno = MESHLINK_EINVAL;
1156 pthread_mutex_lock(&(mesh->mesh_mutex));
1157 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1160 if(mesh->discovery) {
1161 discovery_stop(mesh);
1164 // Shut down the main thread
1165 event_loop_stop(&mesh->loop);
1167 // Send ourselves a UDP packet to kick the event loop
1168 listen_socket_t *s = &mesh->listen_socket[0];
1170 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1) {
1171 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1174 // Wait for the main thread to finish
1175 pthread_mutex_unlock(&(mesh->mesh_mutex));
1176 pthread_join(mesh->thread, NULL);
1177 pthread_mutex_lock(&(mesh->mesh_mutex));
1179 mesh->threadstarted = false;
1181 // Close all metaconnections
1182 if(mesh->connections) {
1183 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1185 connection_t *c = node->data;
1187 terminate_connection(mesh, c, false);
1191 if(mesh->outgoings) {
1192 list_delete_list(mesh->outgoings);
1195 mesh->outgoings = NULL;
1197 pthread_mutex_unlock(&(mesh->mesh_mutex));
1200 void meshlink_close(meshlink_handle_t *mesh) {
1201 if(!mesh || !mesh->confbase) {
1202 meshlink_errno = MESHLINK_EINVAL;
1206 // stop can be called even if mesh has not been started
1207 meshlink_stop(mesh);
1209 // lock is not released after this
1210 pthread_mutex_lock(&(mesh->mesh_mutex));
1212 // Close and free all resources used.
1214 close_network_connections(mesh);
1216 logger(mesh, MESHLINK_INFO, "Terminating");
1218 exit_configuration(&mesh->config);
1219 event_loop_exit(&mesh->loop);
1223 if(mesh->confbase) {
1229 ecdsa_free(mesh->invitation_key);
1232 free(mesh->appname);
1233 free(mesh->confbase);
1234 pthread_mutex_destroy(&(mesh->mesh_mutex));
1236 memset(mesh, 0, sizeof(*mesh));
1241 static void deltree(const char *dirname) {
1242 DIR *d = opendir(dirname);
1247 while((ent = readdir(d))) {
1248 if(ent->d_name[0] == '.') {
1252 char filename[PATH_MAX];
1253 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1255 if(unlink(filename)) {
1267 bool meshlink_destroy(const char *confbase) {
1269 meshlink_errno = MESHLINK_EINVAL;
1273 char filename[PATH_MAX];
1274 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1276 if(unlink(filename)) {
1277 if(errno == ENOENT) {
1278 meshlink_errno = MESHLINK_ENOENT;
1281 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1282 meshlink_errno = MESHLINK_ESTORAGE;
1292 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1294 meshlink_errno = MESHLINK_EINVAL;
1298 pthread_mutex_lock(&(mesh->mesh_mutex));
1299 mesh->receive_cb = cb;
1300 pthread_mutex_unlock(&(mesh->mesh_mutex));
1303 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1305 meshlink_errno = MESHLINK_EINVAL;
1309 pthread_mutex_lock(&(mesh->mesh_mutex));
1310 mesh->node_status_cb = cb;
1311 pthread_mutex_unlock(&(mesh->mesh_mutex));
1314 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1316 pthread_mutex_lock(&(mesh->mesh_mutex));
1318 mesh->log_level = cb ? level : 0;
1319 pthread_mutex_unlock(&(mesh->mesh_mutex));
1322 global_log_level = cb ? level : 0;
1326 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1327 meshlink_packethdr_t *hdr;
1329 // Validate arguments
1330 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1331 meshlink_errno = MESHLINK_EINVAL;
1340 meshlink_errno = MESHLINK_EINVAL;
1344 // Prepare the packet
1345 vpn_packet_t *packet = malloc(sizeof(*packet));
1348 meshlink_errno = MESHLINK_ENOMEM;
1352 packet->probe = false;
1353 packet->tcp = false;
1354 packet->len = len + sizeof(*hdr);
1356 hdr = (meshlink_packethdr_t *)packet->data;
1357 memset(hdr, 0, sizeof(*hdr));
1358 // leave the last byte as 0 to make sure strings are always
1359 // null-terminated if they are longer than the buffer
1360 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1361 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1363 memcpy(packet->data + sizeof(*hdr), data, len);
1366 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1368 meshlink_errno = MESHLINK_ENOMEM;
1372 // Notify event loop
1373 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1378 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1380 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1386 mesh->self->in_packets++;
1387 mesh->self->in_bytes += packet->len;
1388 route(mesh, mesh->self, packet);
1391 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1392 if(!mesh || !destination) {
1393 meshlink_errno = MESHLINK_EINVAL;
1397 pthread_mutex_lock(&(mesh->mesh_mutex));
1399 node_t *n = (node_t *)destination;
1401 if(!n->status.reachable) {
1402 pthread_mutex_unlock(&(mesh->mesh_mutex));
1405 } else if(n->mtuprobes > 30 && n->minmtu) {
1406 pthread_mutex_unlock(&(mesh->mesh_mutex));
1409 pthread_mutex_unlock(&(mesh->mesh_mutex));
1414 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1415 if(!mesh || !node) {
1416 meshlink_errno = MESHLINK_EINVAL;
1420 pthread_mutex_lock(&(mesh->mesh_mutex));
1422 node_t *n = (node_t *)node;
1424 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1425 meshlink_errno = MESHLINK_EINTERNAL;
1426 pthread_mutex_unlock(&(mesh->mesh_mutex));
1430 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1433 meshlink_errno = MESHLINK_EINTERNAL;
1436 pthread_mutex_unlock(&(mesh->mesh_mutex));
1440 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1442 meshlink_errno = MESHLINK_EINVAL;
1446 return (meshlink_node_t *)mesh->self;
1449 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1450 if(!mesh || !name) {
1451 meshlink_errno = MESHLINK_EINVAL;
1455 meshlink_node_t *node = NULL;
1457 pthread_mutex_lock(&(mesh->mesh_mutex));
1458 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1459 pthread_mutex_unlock(&(mesh->mesh_mutex));
1463 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1464 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1465 meshlink_errno = MESHLINK_EINVAL;
1469 meshlink_node_t **result;
1472 pthread_mutex_lock(&(mesh->mesh_mutex));
1474 *nmemb = mesh->nodes->count;
1475 result = realloc(nodes, *nmemb * sizeof(*nodes));
1478 meshlink_node_t **p = result;
1480 for splay_each(node_t, n, mesh->nodes) {
1481 *p++ = (meshlink_node_t *)n;
1486 meshlink_errno = MESHLINK_ENOMEM;
1489 pthread_mutex_unlock(&(mesh->mesh_mutex));
1494 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1495 if(!mesh || !data || !len || !signature || !siglen) {
1496 meshlink_errno = MESHLINK_EINVAL;
1500 if(*siglen < MESHLINK_SIGLEN) {
1501 meshlink_errno = MESHLINK_EINVAL;
1505 pthread_mutex_lock(&(mesh->mesh_mutex));
1507 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1508 meshlink_errno = MESHLINK_EINTERNAL;
1509 pthread_mutex_unlock(&(mesh->mesh_mutex));
1513 *siglen = MESHLINK_SIGLEN;
1514 pthread_mutex_unlock(&(mesh->mesh_mutex));
1518 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1519 if(!mesh || !data || !len || !signature) {
1520 meshlink_errno = MESHLINK_EINVAL;
1524 if(siglen != MESHLINK_SIGLEN) {
1525 meshlink_errno = MESHLINK_EINVAL;
1529 pthread_mutex_lock(&(mesh->mesh_mutex));
1533 struct node_t *n = (struct node_t *)source;
1534 node_read_ecdsa_public_key(mesh, n);
1537 meshlink_errno = MESHLINK_EINTERNAL;
1540 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1543 pthread_mutex_unlock(&(mesh->mesh_mutex));
1547 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1548 char filename[PATH_MAX];
1550 pthread_mutex_lock(&(mesh->mesh_mutex));
1552 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1554 if(mkdir(filename, 0700) && errno != EEXIST) {
1555 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1556 meshlink_errno = MESHLINK_ESTORAGE;
1557 pthread_mutex_unlock(&(mesh->mesh_mutex));
1561 // Count the number of valid invitations, clean up old ones
1562 DIR *dir = opendir(filename);
1565 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1566 meshlink_errno = MESHLINK_ESTORAGE;
1567 pthread_mutex_unlock(&(mesh->mesh_mutex));
1574 time_t deadline = time(NULL) - 604800; // 1 week in the past
1576 while((ent = readdir(dir))) {
1577 if(strlen(ent->d_name) != 24) {
1581 char invname[PATH_MAX];
1583 snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name);
1585 if(!stat(invname, &st)) {
1586 if(mesh->invitation_key && deadline < st.st_mtime) {
1592 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1598 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1600 meshlink_errno = MESHLINK_ESTORAGE;
1601 pthread_mutex_unlock(&(mesh->mesh_mutex));
1607 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1609 // Remove the key if there are no outstanding invitations.
1613 if(mesh->invitation_key) {
1614 ecdsa_free(mesh->invitation_key);
1615 mesh->invitation_key = NULL;
1619 if(mesh->invitation_key) {
1620 pthread_mutex_unlock(&(mesh->mesh_mutex));
1624 // Create a new key if necessary.
1625 FILE *f = fopen(filename, "rb");
1628 if(errno != ENOENT) {
1629 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1630 meshlink_errno = MESHLINK_ESTORAGE;
1631 pthread_mutex_unlock(&(mesh->mesh_mutex));
1635 mesh->invitation_key = ecdsa_generate();
1637 if(!mesh->invitation_key) {
1638 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1639 meshlink_errno = MESHLINK_EINTERNAL;
1640 pthread_mutex_unlock(&(mesh->mesh_mutex));
1644 f = fopen(filename, "wb");
1647 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1648 meshlink_errno = MESHLINK_ESTORAGE;
1649 pthread_mutex_unlock(&(mesh->mesh_mutex));
1653 chmod(filename, 0600);
1654 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1657 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1660 if(!mesh->invitation_key) {
1661 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1662 meshlink_errno = MESHLINK_ESTORAGE;
1666 pthread_mutex_unlock(&(mesh->mesh_mutex));
1667 return mesh->invitation_key;
1670 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1671 if(!mesh || !address) {
1672 meshlink_errno = MESHLINK_EINVAL;
1676 if(!is_valid_hostname(address)) {
1677 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1678 meshlink_errno = MESHLINK_EINVAL;
1684 pthread_mutex_lock(&(mesh->mesh_mutex));
1685 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1686 pthread_mutex_unlock(&(mesh->mesh_mutex));
1691 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1693 meshlink_errno = MESHLINK_EINVAL;
1697 char *address = meshlink_get_external_address(mesh);
1705 pthread_mutex_lock(&(mesh->mesh_mutex));
1706 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1707 pthread_mutex_unlock(&(mesh->mesh_mutex));
1713 int meshlink_get_port(meshlink_handle_t *mesh) {
1715 meshlink_errno = MESHLINK_EINVAL;
1720 meshlink_errno = MESHLINK_EINTERNAL;
1724 return atoi(mesh->myport);
1727 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1728 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1729 meshlink_errno = MESHLINK_EINVAL;
1733 if(mesh->myport && port == atoi(mesh->myport)) {
1737 if(!try_bind(port)) {
1738 meshlink_errno = MESHLINK_ENETWORK;
1744 pthread_mutex_lock(&(mesh->mesh_mutex));
1746 if(mesh->threadstarted) {
1747 meshlink_errno = MESHLINK_EINVAL;
1751 close_network_connections(mesh);
1752 exit_configuration(&mesh->config);
1755 snprintf(portstr, sizeof(portstr), "%d", port);
1756 portstr[sizeof(portstr) - 1] = 0;
1758 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1760 init_configuration(&mesh->config);
1762 if(!read_server_config(mesh)) {
1763 meshlink_errno = MESHLINK_ESTORAGE;
1764 } else if(!setup_network(mesh)) {
1765 meshlink_errno = MESHLINK_ENETWORK;
1771 pthread_mutex_unlock(&(mesh->mesh_mutex));
1776 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1778 meshlink_errno = MESHLINK_EINVAL;
1782 pthread_mutex_lock(&(mesh->mesh_mutex));
1784 // Check validity of the new node's name
1785 if(!check_id(name)) {
1786 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1787 meshlink_errno = MESHLINK_EINVAL;
1788 pthread_mutex_unlock(&(mesh->mesh_mutex));
1792 // Ensure no host configuration file with that name exists
1793 char filename[PATH_MAX];
1794 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1796 if(!access(filename, F_OK)) {
1797 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1798 meshlink_errno = MESHLINK_EEXIST;
1799 pthread_mutex_unlock(&(mesh->mesh_mutex));
1803 // Ensure no other nodes know about this name
1804 if(meshlink_get_node(mesh, name)) {
1805 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1806 meshlink_errno = MESHLINK_EEXIST;
1807 pthread_mutex_unlock(&(mesh->mesh_mutex));
1811 // Get the local address
1812 char *address = get_my_hostname(mesh);
1815 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1816 meshlink_errno = MESHLINK_ERESOLV;
1817 pthread_mutex_unlock(&(mesh->mesh_mutex));
1821 if(!refresh_invitation_key(mesh)) {
1822 meshlink_errno = MESHLINK_EINTERNAL;
1823 pthread_mutex_unlock(&(mesh->mesh_mutex));
1829 // Create a hash of the key.
1830 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1831 sha512(fingerprint, strlen(fingerprint), hash);
1832 b64encode_urlsafe(hash, hash, 18);
1834 // Create a random cookie for this invitation.
1836 randomize(cookie, 18);
1838 // Create a filename that doesn't reveal the cookie itself
1839 char buf[18 + strlen(fingerprint)];
1840 char cookiehash[64];
1841 memcpy(buf, cookie, 18);
1842 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1843 sha512(buf, sizeof(buf), cookiehash);
1844 b64encode_urlsafe(cookiehash, cookiehash, 18);
1846 b64encode_urlsafe(cookie, cookie, 18);
1850 // Create a file containing the details of the invitation.
1851 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1852 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1855 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1856 meshlink_errno = MESHLINK_ESTORAGE;
1857 pthread_mutex_unlock(&(mesh->mesh_mutex));
1861 FILE *f = fdopen(ifd, "w");
1867 // Fill in the details.
1868 fprintf(f, "Name = %s\n", name);
1870 // fprintf(f, "NetName = %s\n", netname);
1871 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1873 // Copy Broadcast and Mode
1874 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1875 FILE *tc = fopen(filename, "r");
1880 while(fgets(buf, sizeof(buf), tc)) {
1881 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1882 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1885 // Make sure there is a newline character.
1886 if(!strchr(buf, '\n')) {
1894 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1895 meshlink_errno = MESHLINK_ESTORAGE;
1896 pthread_mutex_unlock(&(mesh->mesh_mutex));
1900 fprintf(f, "#---------------------------------------------------------------#\n");
1901 fprintf(f, "Name = %s\n", mesh->self->name);
1903 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1907 // Create an URL from the local address, key hash and cookie
1909 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1912 pthread_mutex_unlock(&(mesh->mesh_mutex));
1916 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1917 if(!mesh || !invitation) {
1918 meshlink_errno = MESHLINK_EINVAL;
1922 pthread_mutex_lock(&(mesh->mesh_mutex));
1924 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1925 char copy[strlen(invitation) + 1];
1926 strcpy(copy, invitation);
1928 // Split the invitation URL into hostname, port, key hash and cookie.
1930 char *slash = strchr(copy, '/');
1938 if(strlen(slash) != 48) {
1942 char *address = copy;
1945 if(*address == '[') {
1947 char *bracket = strchr(address, ']');
1955 if(bracket[1] == ':') {
1959 port = strchr(address, ':');
1970 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
1974 // Generate a throw-away key for the invitation.
1975 ecdsa_t *key = ecdsa_generate();
1978 meshlink_errno = MESHLINK_EINTERNAL;
1979 pthread_mutex_unlock(&(mesh->mesh_mutex));
1983 char *b64key = ecdsa_get_base64_public_key(key);
1985 //Before doing meshlink_join make sure we are not connected to another mesh
1986 if(mesh->threadstarted) {
1990 // Connect to the meshlink daemon mentioned in the URL.
1991 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1994 meshlink_errno = MESHLINK_ERESOLV;
1995 pthread_mutex_unlock(&(mesh->mesh_mutex));
1999 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2001 if(mesh->sock <= 0) {
2002 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2004 meshlink_errno = MESHLINK_ENETWORK;
2005 pthread_mutex_unlock(&(mesh->mesh_mutex));
2009 set_timeout(mesh->sock, 5000);
2011 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
2012 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2013 closesocket(mesh->sock);
2015 meshlink_errno = MESHLINK_ENETWORK;
2016 pthread_mutex_unlock(&(mesh->mesh_mutex));
2022 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2024 // Tell him we have an invitation, and give him our throw-away key.
2028 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2029 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2030 closesocket(mesh->sock);
2031 meshlink_errno = MESHLINK_ENETWORK;
2032 pthread_mutex_unlock(&(mesh->mesh_mutex));
2038 char hisname[4096] = "";
2039 int code, hismajor, hisminor = 0;
2041 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) {
2042 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2043 closesocket(mesh->sock);
2044 meshlink_errno = MESHLINK_ENETWORK;
2045 pthread_mutex_unlock(&(mesh->mesh_mutex));
2049 // Check if the hash of the key he gave us matches the hash in the URL.
2050 char *fingerprint = mesh->line + 2;
2053 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2054 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2055 meshlink_errno = MESHLINK_EINTERNAL;
2056 pthread_mutex_unlock(&(mesh->mesh_mutex));
2060 if(memcmp(hishash, mesh->hash, 18)) {
2061 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2062 meshlink_errno = MESHLINK_EPEER;
2063 pthread_mutex_unlock(&(mesh->mesh_mutex));
2068 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2071 meshlink_errno = MESHLINK_EINTERNAL;
2072 pthread_mutex_unlock(&(mesh->mesh_mutex));
2076 // Start an SPTPS session
2077 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2078 meshlink_errno = MESHLINK_EINTERNAL;
2079 pthread_mutex_unlock(&(mesh->mesh_mutex));
2083 // Feed rest of input buffer to SPTPS
2084 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2085 meshlink_errno = MESHLINK_EPEER;
2086 pthread_mutex_unlock(&(mesh->mesh_mutex));
2092 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2094 if(errno == EINTR) {
2098 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2099 meshlink_errno = MESHLINK_ENETWORK;
2100 pthread_mutex_unlock(&(mesh->mesh_mutex));
2104 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2105 meshlink_errno = MESHLINK_EPEER;
2106 pthread_mutex_unlock(&(mesh->mesh_mutex));
2111 sptps_stop(&mesh->sptps);
2114 closesocket(mesh->sock);
2116 if(!mesh->success) {
2117 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2118 meshlink_errno = MESHLINK_EPEER;
2119 pthread_mutex_unlock(&(mesh->mesh_mutex));
2123 pthread_mutex_unlock(&(mesh->mesh_mutex));
2127 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
2128 meshlink_errno = MESHLINK_EINVAL;
2129 pthread_mutex_unlock(&(mesh->mesh_mutex));
2133 char *meshlink_export(meshlink_handle_t *mesh) {
2135 meshlink_errno = MESHLINK_EINVAL;
2139 pthread_mutex_lock(&(mesh->mesh_mutex));
2141 char filename[PATH_MAX];
2142 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2143 FILE *f = fopen(filename, "r");
2146 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2147 meshlink_errno = MESHLINK_ESTORAGE;
2148 pthread_mutex_unlock(&(mesh->mesh_mutex));
2152 fseek(f, 0, SEEK_END);
2153 int fsize = ftell(f);
2156 size_t len = fsize + 9 + strlen(mesh->self->name);
2157 char *buf = xmalloc(len);
2158 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2160 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2161 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2164 meshlink_errno = MESHLINK_ESTORAGE;
2165 pthread_mutex_unlock(&(mesh->mesh_mutex));
2172 pthread_mutex_unlock(&(mesh->mesh_mutex));
2176 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2177 if(!mesh || !data) {
2178 meshlink_errno = MESHLINK_EINVAL;
2182 pthread_mutex_lock(&(mesh->mesh_mutex));
2184 if(strncmp(data, "Name = ", 7)) {
2185 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2186 meshlink_errno = MESHLINK_EPEER;
2187 pthread_mutex_unlock(&(mesh->mesh_mutex));
2191 char *end = strchr(data + 7, '\n');
2194 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2195 meshlink_errno = MESHLINK_EPEER;
2196 pthread_mutex_unlock(&(mesh->mesh_mutex));
2200 int len = end - (data + 7);
2202 memcpy(name, data + 7, len);
2205 if(!check_id(name)) {
2206 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2207 meshlink_errno = MESHLINK_EPEER;
2208 pthread_mutex_unlock(&(mesh->mesh_mutex));
2212 char filename[PATH_MAX];
2213 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2215 if(!access(filename, F_OK)) {
2216 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2217 meshlink_errno = MESHLINK_EEXIST;
2218 pthread_mutex_unlock(&(mesh->mesh_mutex));
2222 if(errno != ENOENT) {
2223 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2224 meshlink_errno = MESHLINK_ESTORAGE;
2225 pthread_mutex_unlock(&(mesh->mesh_mutex));
2229 FILE *f = fopen(filename, "w");
2232 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2233 meshlink_errno = MESHLINK_ESTORAGE;
2234 pthread_mutex_unlock(&(mesh->mesh_mutex));
2238 fwrite(end + 1, strlen(end + 1), 1, f);
2241 load_all_nodes(mesh);
2243 pthread_mutex_unlock(&(mesh->mesh_mutex));
2247 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2248 if(!mesh || !node) {
2249 meshlink_errno = MESHLINK_EINVAL;
2253 pthread_mutex_lock(&(mesh->mesh_mutex));
2257 n->status.blacklisted = true;
2258 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2260 //Make blacklisting persistent in the config file
2261 append_config_file(mesh, n->name, "blacklisted", "yes");
2263 pthread_mutex_unlock(&(mesh->mesh_mutex));
2267 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2268 if(!mesh || !node) {
2269 meshlink_errno = MESHLINK_EINVAL;
2273 pthread_mutex_lock(&(mesh->mesh_mutex));
2275 node_t *n = (node_t *)node;
2276 n->status.blacklisted = false;
2278 //TODO: remove blacklisted = yes from the config file
2280 pthread_mutex_unlock(&(mesh->mesh_mutex));
2284 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2285 mesh->default_blacklist = blacklist;
2288 /* Hint that a hostname may be found at an address
2289 * See header file for detailed comment.
2291 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2292 if(!mesh || !node || !addr) {
2296 // Ignore hints about ourself.
2297 if((node_t *)node == mesh->self) {
2301 pthread_mutex_lock(&(mesh->mesh_mutex));
2303 char *host = NULL, *port = NULL, *str = NULL;
2304 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2307 xasprintf(&str, "%s %s", host, port);
2309 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2310 modify_config_file(mesh, node->name, "Address", str, 5);
2312 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2320 pthread_mutex_unlock(&(mesh->mesh_mutex));
2321 // @TODO do we want to fire off a connection attempt right away?
2324 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2326 node_t *n = utcp->priv;
2327 meshlink_handle_t *mesh = n->mesh;
2328 return mesh->channel_accept_cb;
2331 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2332 meshlink_channel_t *channel = connection->priv;
2338 node_t *n = channel->node;
2339 meshlink_handle_t *mesh = n->mesh;
2341 if(n->status.destroyed) {
2342 meshlink_channel_close(mesh, channel);
2343 } else if(channel->receive_cb) {
2344 channel->receive_cb(mesh, channel, data, len);
2350 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2351 node_t *n = utcp_connection->utcp->priv;
2357 meshlink_handle_t *mesh = n->mesh;
2359 if(!mesh->channel_accept_cb) {
2363 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2365 channel->c = utcp_connection;
2367 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2368 utcp_accept(utcp_connection, channel_recv, channel);
2374 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2375 node_t *n = utcp->priv;
2376 meshlink_handle_t *mesh = n->mesh;
2377 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2380 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2381 if(!mesh || !channel) {
2382 meshlink_errno = MESHLINK_EINVAL;
2386 channel->receive_cb = cb;
2389 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2391 node_t *n = (node_t *)source;
2397 utcp_recv(n->utcp, data, len);
2400 static void channel_poll(struct utcp_connection *connection, size_t len) {
2401 meshlink_channel_t *channel = connection->priv;
2407 node_t *n = channel->node;
2408 meshlink_handle_t *mesh = n->mesh;
2410 if(channel->poll_cb) {
2411 channel->poll_cb(mesh, channel, len);
2415 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2417 channel->poll_cb = cb;
2418 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2421 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2423 meshlink_errno = MESHLINK_EINVAL;
2427 pthread_mutex_lock(&mesh->mesh_mutex);
2428 mesh->channel_accept_cb = cb;
2429 mesh->receive_cb = channel_receive;
2431 for splay_each(node_t, n, mesh->nodes) {
2432 if(!n->utcp && n != mesh->self) {
2433 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2437 pthread_mutex_unlock(&mesh->mesh_mutex);
2440 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) {
2442 abort(); // TODO: handle non-NULL data
2445 if(!mesh || !node) {
2446 meshlink_errno = MESHLINK_EINVAL;
2450 node_t *n = (node_t *)node;
2453 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2454 mesh->receive_cb = channel_receive;
2457 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2462 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2464 channel->receive_cb = cb;
2465 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2468 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2476 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) {
2477 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2480 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2481 if(!mesh || !channel) {
2482 meshlink_errno = MESHLINK_EINVAL;
2486 utcp_shutdown(channel->c, direction);
2489 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2490 if(!mesh || !channel) {
2491 meshlink_errno = MESHLINK_EINVAL;
2495 utcp_close(channel->c);
2499 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2500 if(!mesh || !channel) {
2501 meshlink_errno = MESHLINK_EINVAL;
2510 meshlink_errno = MESHLINK_EINVAL;
2514 // TODO: more finegrained locking.
2515 // Ideally we want to put the data into the UTCP connection's send buffer.
2516 // Then, preferrably only if there is room in the receiver window,
2517 // kick the meshlink thread to go send packets.
2519 pthread_mutex_lock(&mesh->mesh_mutex);
2520 ssize_t retval = utcp_send(channel->c, data, len);
2521 pthread_mutex_unlock(&mesh->mesh_mutex);
2524 meshlink_errno = MESHLINK_ENETWORK;
2530 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2531 if(!mesh || !channel) {
2532 meshlink_errno = MESHLINK_EINVAL;
2536 return channel->c->flags;
2539 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2540 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2541 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2544 if(mesh->node_status_cb) {
2545 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2549 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2551 meshlink_errno = MESHLINK_EINVAL;
2555 pthread_mutex_lock(&mesh->mesh_mutex);
2557 if(mesh->discovery == enable) {
2561 if(mesh->threadstarted) {
2563 discovery_start(mesh);
2565 discovery_stop(mesh);
2569 mesh->discovery = enable;
2572 pthread_mutex_unlock(&mesh->mesh_mutex);
2575 static void __attribute__((constructor)) meshlink_init(void) {
2578 randomize(&seed, sizeof(seed));
2582 static void __attribute__((destructor)) meshlink_exit(void) {
2586 /// Device class traits
2587 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2588 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2589 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2590 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2591 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN