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 ");
180 // q is now pointing to the hostname
182 p = q + strcspn(q, "\t ");
188 p += strspn(p, "\t ");
189 p[strcspn(p, "\t ")] = 0;
190 // p is now pointing to the port
192 // Check that the hostname is a symbolic name (it's not a numeric IPv4 or IPv6 address)
193 if(!q[strspn(q, "0123456789.")] || strchr(q, ':')) {
197 if(!*port && !strcasecmp(line, "Port")) {
199 } else if(!*hostname && !strcasecmp(line, "Address")) {
200 *hostname = xstrdup(q);
208 if(*hostname && *port) {
216 static bool is_valid_hostname(const char *hostname) {
217 for(const char *p = hostname; *p; p++) {
218 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
226 static void set_timeout(int sock, int timeout) {
231 tv.tv_sec = timeout / 1000;
232 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
234 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
235 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
238 // Find out what local address a socket would use if we connect to the given address.
239 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
240 // of both endpoints, but this will actually not send any UDP packet.
241 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
242 struct addrinfo *rai = NULL;
243 const struct addrinfo hint = {
244 .ai_family = AF_UNSPEC,
245 .ai_socktype = SOCK_DGRAM,
246 .ai_protocol = IPPROTO_UDP,
249 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
253 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
260 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
267 struct sockaddr_storage sn;
268 socklen_t sl = sizeof(sn);
270 if(getsockname(sock, (struct sockaddr *)&sn, &sl)) {
274 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
281 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
282 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
285 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
286 char *hostname = NULL;
288 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
289 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
290 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
293 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
294 if(family != AF_UNSPEC && aip->ai_family != family) {
298 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
301 set_timeout(s, 5000);
303 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
310 send(s, request, sizeof(request) - 1, 0);
311 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
316 if(line[len - 1] == '\n') {
320 char *p = strrchr(line, '\n');
323 hostname = xstrdup(p + 1);
339 // Check that the hostname is reasonable
340 if(hostname && !is_valid_hostname(hostname)) {
345 // If there is no hostname, determine the address used for an outgoing connection.
347 char localaddr[NI_MAXHOST];
348 bool success = false;
350 if(family == AF_INET) {
351 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
352 } else if(family == AF_INET6) {
353 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
357 hostname = xstrdup(localaddr);
362 meshlink_errno = MESHLINK_ERESOLV;
368 // This gets the hostname part for use in invitation URLs
369 static char *get_my_hostname(meshlink_handle_t *mesh) {
370 char *hostname[2] = {NULL};
372 char *hostport = NULL;
373 char *name = mesh->self->name;
374 char filename[PATH_MAX] = "";
376 // Use first Address statement in own host config file
377 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
378 scan_for_hostname(filename, &hostname[0], &port);
384 hostname[0] = meshlink_get_external_address_for_family(mesh, AF_INET);
385 hostname[1] = meshlink_get_external_address_for_family(mesh, AF_INET6);
387 if(!hostname[0] && !hostname[1]) {
391 if(!strcmp(hostname[0], hostname[1])) {
396 port = xstrdup(mesh->myport);
398 for(int i = 0; i < 2; i++) {
401 xasprintf(&tmphostport, "%s %s", hostname[i], port);
402 append_config_file(mesh, mesh->self->name, "Address", tmphostport);
409 for(int i = 0; i < 2; i++) {
415 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]" : "%s%s%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i]);
418 hostport = newhostport;
423 xasprintf(&newhostport, "%s:%s", hostport, port);
426 hostport = newhostport;
432 static char *get_line(const char **data) {
433 if(!data || !*data) {
442 static char line[1024];
443 const char *end = strchr(*data, '\n');
444 size_t len = end ? (size_t)(end - *data) : strlen(*data);
446 if(len >= sizeof(line)) {
447 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
451 if(len && !isprint(**data)) {
455 memcpy(line, *data, len);
467 static char *get_value(const char *data, const char *var) {
468 char *line = get_line(&data);
474 char *sep = line + strcspn(line, " \t=");
475 char *val = sep + strspn(sep, " \t");
478 val += 1 + strspn(val + 1, " \t");
483 if(strcasecmp(line, var)) {
490 static bool try_bind(int port) {
491 struct addrinfo *ai = NULL;
492 struct addrinfo hint = {
493 .ai_flags = AI_PASSIVE,
494 .ai_family = AF_UNSPEC,
495 .ai_socktype = SOCK_STREAM,
496 .ai_protocol = IPPROTO_TCP,
500 snprintf(portstr, sizeof(portstr), "%d", port);
502 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
507 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
514 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
529 int check_port(meshlink_handle_t *mesh) {
530 for(int i = 0; i < 1000; i++) {
531 int port = 0x1000 + (rand() & 0x7fff);
534 char filename[PATH_MAX];
535 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
536 FILE *f = fopen(filename, "a");
539 meshlink_errno = MESHLINK_ESTORAGE;
540 logger(mesh, MESHLINK_DEBUG, "Could not store Port.\n");
544 fprintf(f, "Port = %d\n", port);
550 meshlink_errno = MESHLINK_ENETWORK;
551 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
555 static bool finalize_join(meshlink_handle_t *mesh) {
556 char *name = xstrdup(get_value(mesh->data, "Name"));
559 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
563 if(!check_id(name)) {
564 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
568 char filename[PATH_MAX];
569 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
571 FILE *f = fopen(filename, "w");
574 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
578 fprintf(f, "Name = %s\n", name);
580 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
581 FILE *fh = fopen(filename, "w");
584 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
589 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
590 // Other chunks go unfiltered to their respective host config files
591 const char *p = mesh->data;
594 while((l = get_line(&p))) {
600 // Split line into variable and value
601 int len = strcspn(l, "\t =");
603 value += strspn(value, "\t ");
607 value += strspn(value, "\t ");
613 if(!strcasecmp(l, "Name"))
614 if(strcmp(value, name)) {
618 } else if(!strcasecmp(l, "NetName")) {
622 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
626 for(i = 0; variables[i].name; i++) {
627 if(strcasecmp(l, variables[i].name)) {
635 // Ignore unknown and unsafe variables
637 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
639 } else if(!(variables[i].type & VAR_SAFE)) {
640 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
644 // Copy the safe variable to the right config file
645 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
650 while(l && !strcasecmp(l, "Name")) {
651 if(!check_id(value)) {
652 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
656 if(!strcmp(value, name)) {
657 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
661 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
662 f = fopen(filename, "w");
665 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
669 while((l = get_line(&p))) {
670 if(!strcmp(l, "#---------------------------------------------------------------#")) {
674 int len = strcspn(l, "\t =");
676 if(len == 4 && !strncasecmp(l, "Name", 4)) {
678 value += strspn(value, "\t ");
682 value += strspn(value, "\t ");
696 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
703 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
704 fprintf(fh, "Port = %s\n", mesh->myport);
708 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
711 free(mesh->self->name);
712 free(mesh->self->connection->name);
713 mesh->self->name = xstrdup(name);
714 mesh->self->connection->name = name;
716 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
718 load_all_nodes(mesh);
723 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
725 meshlink_handle_t *mesh = handle;
726 const char *ptr = data;
729 int result = send(mesh->sock, ptr, len, 0);
731 if(result == -1 && errno == EINTR) {
733 } else if(result <= 0) {
744 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
745 meshlink_handle_t *mesh = handle;
748 case SPTPS_HANDSHAKE:
749 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
752 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
753 memcpy(mesh->data + mesh->thedatalen, msg, len);
754 mesh->thedatalen += len;
755 mesh->data[mesh->thedatalen] = 0;
759 mesh->thedatalen = 0;
760 return finalize_join(mesh);
763 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
764 shutdown(mesh->sock, SHUT_RDWR);
765 mesh->success = true;
775 static bool recvline(meshlink_handle_t *mesh, size_t len) {
776 char *newline = NULL;
782 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
783 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
785 if(result == -1 && errno == EINTR) {
787 } else if(result <= 0) {
791 mesh->blen += result;
794 if((size_t)(newline - mesh->buffer) >= len) {
798 len = newline - mesh->buffer;
800 memcpy(mesh->line, mesh->buffer, len);
802 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
803 mesh->blen -= len + 1;
807 static bool sendline(int fd, char *format, ...) {
808 static char buffer[4096];
813 va_start(ap, format);
814 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
817 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
825 int result = send(fd, p, blen, MSG_NOSIGNAL);
827 if(result == -1 && errno == EINTR) {
829 } else if(result <= 0) {
840 static const char *errstr[] = {
841 [MESHLINK_OK] = "No error",
842 [MESHLINK_EINVAL] = "Invalid argument",
843 [MESHLINK_ENOMEM] = "Out of memory",
844 [MESHLINK_ENOENT] = "No such node",
845 [MESHLINK_EEXIST] = "Node already exists",
846 [MESHLINK_EINTERNAL] = "Internal error",
847 [MESHLINK_ERESOLV] = "Could not resolve hostname",
848 [MESHLINK_ESTORAGE] = "Storage error",
849 [MESHLINK_ENETWORK] = "Network error",
850 [MESHLINK_EPEER] = "Error communicating with peer",
853 const char *meshlink_strerror(meshlink_errno_t err) {
854 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
855 return "Invalid error code";
861 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
864 char pubname[PATH_MAX], privname[PATH_MAX];
866 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
868 if(!(key = ecdsa_generate())) {
869 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
870 meshlink_errno = MESHLINK_EINTERNAL;
873 logger(mesh, MESHLINK_DEBUG, "Done.\n");
876 if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
877 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
878 meshlink_errno = MESHLINK_ESTORAGE;
882 f = fopen(privname, "wb");
885 meshlink_errno = MESHLINK_ESTORAGE;
890 fchmod(fileno(f), 0600);
893 if(!ecdsa_write_pem_private_key(key, f)) {
894 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
897 meshlink_errno = MESHLINK_EINTERNAL;
903 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
904 f = fopen(pubname, "a");
907 meshlink_errno = MESHLINK_ESTORAGE;
911 char *pubkey = ecdsa_get_base64_public_key(key);
912 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
921 static struct timeval idle(event_loop_t *loop, void *data) {
923 meshlink_handle_t *mesh = data;
924 struct timeval t, tmin = {3600, 0};
926 for splay_each(node_t, n, mesh->nodes) {
931 t = utcp_timeout(n->utcp);
933 if(timercmp(&t, &tmin, <)) {
941 // Get our local address(es) by simulating connecting to an Internet host.
942 static void add_local_addresses(meshlink_handle_t *mesh) {
943 char host[NI_MAXHOST];
944 char entry[MAX_STRING_SIZE];
948 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
949 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
950 append_config_file(mesh, mesh->name, "Address", entry);
955 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
956 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
957 append_config_file(mesh, mesh->name, "Address", entry);
961 static bool meshlink_setup(meshlink_handle_t *mesh) {
962 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
963 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
964 meshlink_errno = MESHLINK_ESTORAGE;
968 char filename[PATH_MAX];
969 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
971 if(mkdir(filename, 0777) && errno != EEXIST) {
972 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
973 meshlink_errno = MESHLINK_ESTORAGE;
977 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
979 if(!access(filename, F_OK)) {
980 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
981 meshlink_errno = MESHLINK_EEXIST;
985 FILE *f = fopen(filename, "w");
988 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
989 meshlink_errno = MESHLINK_ESTORAGE;
993 fprintf(f, "Name = %s\n", mesh->name);
996 if(!ecdsa_keygen(mesh)) {
997 meshlink_errno = MESHLINK_EINTERNAL;
1002 if(check_port(mesh) == 0) {
1003 meshlink_errno = MESHLINK_ENETWORK;
1011 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1012 // Validate arguments provided by the application
1013 bool usingname = false;
1015 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1017 if(!confbase || !*confbase) {
1018 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1019 meshlink_errno = MESHLINK_EINVAL;
1023 if(!appname || !*appname) {
1024 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1025 meshlink_errno = MESHLINK_EINVAL;
1029 if(!name || !*name) {
1030 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1032 } else { //check name only if there is a name != NULL
1034 if(!check_id(name)) {
1035 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1036 meshlink_errno = MESHLINK_EINVAL;
1043 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1044 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1045 meshlink_errno = MESHLINK_EINVAL;
1049 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1050 mesh->confbase = xstrdup(confbase);
1051 mesh->appname = xstrdup(appname);
1052 mesh->devclass = devclass;
1053 mesh->discovery = true;
1056 mesh->name = xstrdup(name);
1060 pthread_mutexattr_t attr;
1061 pthread_mutexattr_init(&attr);
1062 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1063 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1065 mesh->threadstarted = false;
1066 event_loop_init(&mesh->loop);
1067 mesh->loop.data = mesh;
1069 meshlink_queue_init(&mesh->outpacketqueue);
1071 // Check whether meshlink.conf already exists
1073 char filename[PATH_MAX];
1074 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1076 if(access(filename, R_OK)) {
1077 if(errno == ENOENT) {
1078 // If not, create it
1079 if(!meshlink_setup(mesh)) {
1080 // meshlink_errno is set by meshlink_setup()
1084 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1085 meshlink_close(mesh);
1086 meshlink_errno = MESHLINK_ESTORAGE;
1091 // Read the configuration
1093 init_configuration(&mesh->config);
1095 if(!read_server_config(mesh)) {
1096 meshlink_close(mesh);
1097 meshlink_errno = MESHLINK_ESTORAGE;
1102 struct WSAData wsa_state;
1104 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1108 // Setup up everything
1109 // TODO: we should not open listening sockets yet
1111 if(!setup_network(mesh)) {
1112 meshlink_close(mesh);
1113 meshlink_errno = MESHLINK_ENETWORK;
1117 add_local_addresses(mesh);
1119 idle_set(&mesh->loop, idle, mesh);
1121 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1125 static void *meshlink_main_loop(void *arg) {
1126 meshlink_handle_t *mesh = arg;
1128 pthread_mutex_lock(&(mesh->mesh_mutex));
1130 try_outgoing_connections(mesh);
1132 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1134 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1136 pthread_mutex_unlock(&(mesh->mesh_mutex));
1140 bool meshlink_start(meshlink_handle_t *mesh) {
1142 meshlink_errno = MESHLINK_EINVAL;
1146 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1148 pthread_mutex_lock(&(mesh->mesh_mutex));
1150 if(mesh->threadstarted) {
1151 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1152 pthread_mutex_unlock(&(mesh->mesh_mutex));
1156 if(mesh->listen_socket[0].tcp.fd < 0) {
1157 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1158 meshlink_errno = MESHLINK_ENETWORK;
1162 mesh->thedatalen = 0;
1164 // TODO: open listening sockets first
1166 //Check that a valid name is set
1168 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1169 meshlink_errno = MESHLINK_EINVAL;
1170 pthread_mutex_unlock(&(mesh->mesh_mutex));
1174 // Start the main thread
1176 event_loop_start(&mesh->loop);
1178 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1179 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1180 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1181 meshlink_errno = MESHLINK_EINTERNAL;
1182 pthread_mutex_unlock(&(mesh->mesh_mutex));
1186 mesh->threadstarted = true;
1188 if(mesh->discovery) {
1189 discovery_start(mesh);
1192 pthread_mutex_unlock(&(mesh->mesh_mutex));
1196 void meshlink_stop(meshlink_handle_t *mesh) {
1198 meshlink_errno = MESHLINK_EINVAL;
1202 pthread_mutex_lock(&(mesh->mesh_mutex));
1203 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1206 if(mesh->discovery) {
1207 discovery_stop(mesh);
1210 // Shut down the main thread
1211 event_loop_stop(&mesh->loop);
1213 // Send ourselves a UDP packet to kick the event loop
1214 listen_socket_t *s = &mesh->listen_socket[0];
1216 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1) {
1217 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1220 // Wait for the main thread to finish
1221 pthread_mutex_unlock(&(mesh->mesh_mutex));
1222 pthread_join(mesh->thread, NULL);
1223 pthread_mutex_lock(&(mesh->mesh_mutex));
1225 mesh->threadstarted = false;
1227 // Close all metaconnections
1228 if(mesh->connections) {
1229 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1231 connection_t *c = node->data;
1233 terminate_connection(mesh, c, false);
1237 if(mesh->outgoings) {
1238 list_delete_list(mesh->outgoings);
1241 mesh->outgoings = NULL;
1243 pthread_mutex_unlock(&(mesh->mesh_mutex));
1246 void meshlink_close(meshlink_handle_t *mesh) {
1247 if(!mesh || !mesh->confbase) {
1248 meshlink_errno = MESHLINK_EINVAL;
1252 // stop can be called even if mesh has not been started
1253 meshlink_stop(mesh);
1255 // lock is not released after this
1256 pthread_mutex_lock(&(mesh->mesh_mutex));
1258 // Close and free all resources used.
1260 close_network_connections(mesh);
1262 logger(mesh, MESHLINK_INFO, "Terminating");
1264 exit_configuration(&mesh->config);
1265 event_loop_exit(&mesh->loop);
1269 if(mesh->confbase) {
1275 ecdsa_free(mesh->invitation_key);
1278 free(mesh->appname);
1279 free(mesh->confbase);
1280 pthread_mutex_destroy(&(mesh->mesh_mutex));
1282 memset(mesh, 0, sizeof(*mesh));
1287 static void deltree(const char *dirname) {
1288 DIR *d = opendir(dirname);
1293 while((ent = readdir(d))) {
1294 if(ent->d_name[0] == '.') {
1298 char filename[PATH_MAX];
1299 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1301 if(unlink(filename)) {
1313 bool meshlink_destroy(const char *confbase) {
1315 meshlink_errno = MESHLINK_EINVAL;
1319 char filename[PATH_MAX];
1320 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1322 if(unlink(filename)) {
1323 if(errno == ENOENT) {
1324 meshlink_errno = MESHLINK_ENOENT;
1327 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1328 meshlink_errno = MESHLINK_ESTORAGE;
1338 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1340 meshlink_errno = MESHLINK_EINVAL;
1344 pthread_mutex_lock(&(mesh->mesh_mutex));
1345 mesh->receive_cb = cb;
1346 pthread_mutex_unlock(&(mesh->mesh_mutex));
1349 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1351 meshlink_errno = MESHLINK_EINVAL;
1355 pthread_mutex_lock(&(mesh->mesh_mutex));
1356 mesh->node_status_cb = cb;
1357 pthread_mutex_unlock(&(mesh->mesh_mutex));
1360 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1362 pthread_mutex_lock(&(mesh->mesh_mutex));
1364 mesh->log_level = cb ? level : 0;
1365 pthread_mutex_unlock(&(mesh->mesh_mutex));
1368 global_log_level = cb ? level : 0;
1372 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1373 meshlink_packethdr_t *hdr;
1375 // Validate arguments
1376 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1377 meshlink_errno = MESHLINK_EINVAL;
1386 meshlink_errno = MESHLINK_EINVAL;
1390 // Prepare the packet
1391 vpn_packet_t *packet = malloc(sizeof(*packet));
1394 meshlink_errno = MESHLINK_ENOMEM;
1398 packet->probe = false;
1399 packet->tcp = false;
1400 packet->len = len + sizeof(*hdr);
1402 hdr = (meshlink_packethdr_t *)packet->data;
1403 memset(hdr, 0, sizeof(*hdr));
1404 // leave the last byte as 0 to make sure strings are always
1405 // null-terminated if they are longer than the buffer
1406 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1407 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1409 memcpy(packet->data + sizeof(*hdr), data, len);
1412 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1414 meshlink_errno = MESHLINK_ENOMEM;
1418 // Notify event loop
1419 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1424 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1426 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1432 mesh->self->in_packets++;
1433 mesh->self->in_bytes += packet->len;
1434 route(mesh, mesh->self, packet);
1437 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1438 if(!mesh || !destination) {
1439 meshlink_errno = MESHLINK_EINVAL;
1443 pthread_mutex_lock(&(mesh->mesh_mutex));
1445 node_t *n = (node_t *)destination;
1447 if(!n->status.reachable) {
1448 pthread_mutex_unlock(&(mesh->mesh_mutex));
1451 } else if(n->mtuprobes > 30 && n->minmtu) {
1452 pthread_mutex_unlock(&(mesh->mesh_mutex));
1455 pthread_mutex_unlock(&(mesh->mesh_mutex));
1460 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1461 if(!mesh || !node) {
1462 meshlink_errno = MESHLINK_EINVAL;
1466 pthread_mutex_lock(&(mesh->mesh_mutex));
1468 node_t *n = (node_t *)node;
1470 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1471 meshlink_errno = MESHLINK_EINTERNAL;
1472 pthread_mutex_unlock(&(mesh->mesh_mutex));
1476 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1479 meshlink_errno = MESHLINK_EINTERNAL;
1482 pthread_mutex_unlock(&(mesh->mesh_mutex));
1486 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1488 meshlink_errno = MESHLINK_EINVAL;
1492 return (meshlink_node_t *)mesh->self;
1495 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1496 if(!mesh || !name) {
1497 meshlink_errno = MESHLINK_EINVAL;
1501 meshlink_node_t *node = NULL;
1503 pthread_mutex_lock(&(mesh->mesh_mutex));
1504 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1505 pthread_mutex_unlock(&(mesh->mesh_mutex));
1509 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1510 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1511 meshlink_errno = MESHLINK_EINVAL;
1515 meshlink_node_t **result;
1518 pthread_mutex_lock(&(mesh->mesh_mutex));
1520 *nmemb = mesh->nodes->count;
1521 result = realloc(nodes, *nmemb * sizeof(*nodes));
1524 meshlink_node_t **p = result;
1526 for splay_each(node_t, n, mesh->nodes) {
1527 *p++ = (meshlink_node_t *)n;
1532 meshlink_errno = MESHLINK_ENOMEM;
1535 pthread_mutex_unlock(&(mesh->mesh_mutex));
1540 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1541 if(!mesh || !data || !len || !signature || !siglen) {
1542 meshlink_errno = MESHLINK_EINVAL;
1546 if(*siglen < MESHLINK_SIGLEN) {
1547 meshlink_errno = MESHLINK_EINVAL;
1551 pthread_mutex_lock(&(mesh->mesh_mutex));
1553 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1554 meshlink_errno = MESHLINK_EINTERNAL;
1555 pthread_mutex_unlock(&(mesh->mesh_mutex));
1559 *siglen = MESHLINK_SIGLEN;
1560 pthread_mutex_unlock(&(mesh->mesh_mutex));
1564 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1565 if(!mesh || !data || !len || !signature) {
1566 meshlink_errno = MESHLINK_EINVAL;
1570 if(siglen != MESHLINK_SIGLEN) {
1571 meshlink_errno = MESHLINK_EINVAL;
1575 pthread_mutex_lock(&(mesh->mesh_mutex));
1579 struct node_t *n = (struct node_t *)source;
1580 node_read_ecdsa_public_key(mesh, n);
1583 meshlink_errno = MESHLINK_EINTERNAL;
1586 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1589 pthread_mutex_unlock(&(mesh->mesh_mutex));
1593 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1594 char filename[PATH_MAX];
1596 pthread_mutex_lock(&(mesh->mesh_mutex));
1598 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1600 if(mkdir(filename, 0700) && errno != EEXIST) {
1601 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1602 meshlink_errno = MESHLINK_ESTORAGE;
1603 pthread_mutex_unlock(&(mesh->mesh_mutex));
1607 // Count the number of valid invitations, clean up old ones
1608 DIR *dir = opendir(filename);
1611 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1612 meshlink_errno = MESHLINK_ESTORAGE;
1613 pthread_mutex_unlock(&(mesh->mesh_mutex));
1620 time_t deadline = time(NULL) - 604800; // 1 week in the past
1622 while((ent = readdir(dir))) {
1623 if(strlen(ent->d_name) != 24) {
1627 char invname[PATH_MAX];
1630 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1631 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1635 if(!stat(invname, &st)) {
1636 if(mesh->invitation_key && deadline < st.st_mtime) {
1642 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1648 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1650 meshlink_errno = MESHLINK_ESTORAGE;
1651 pthread_mutex_unlock(&(mesh->mesh_mutex));
1657 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1659 // Remove the key if there are no outstanding invitations.
1663 if(mesh->invitation_key) {
1664 ecdsa_free(mesh->invitation_key);
1665 mesh->invitation_key = NULL;
1669 if(mesh->invitation_key) {
1670 pthread_mutex_unlock(&(mesh->mesh_mutex));
1674 // Create a new key if necessary.
1675 FILE *f = fopen(filename, "rb");
1678 if(errno != ENOENT) {
1679 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1680 meshlink_errno = MESHLINK_ESTORAGE;
1681 pthread_mutex_unlock(&(mesh->mesh_mutex));
1685 mesh->invitation_key = ecdsa_generate();
1687 if(!mesh->invitation_key) {
1688 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1689 meshlink_errno = MESHLINK_EINTERNAL;
1690 pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 f = fopen(filename, "wb");
1697 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1698 meshlink_errno = MESHLINK_ESTORAGE;
1699 pthread_mutex_unlock(&(mesh->mesh_mutex));
1703 chmod(filename, 0600);
1704 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1707 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1710 if(!mesh->invitation_key) {
1711 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1712 meshlink_errno = MESHLINK_ESTORAGE;
1716 pthread_mutex_unlock(&(mesh->mesh_mutex));
1717 return mesh->invitation_key;
1720 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1721 if(!mesh || !address) {
1722 meshlink_errno = MESHLINK_EINVAL;
1726 if(!is_valid_hostname(address)) {
1727 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1728 meshlink_errno = MESHLINK_EINVAL;
1734 pthread_mutex_lock(&(mesh->mesh_mutex));
1735 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1736 pthread_mutex_unlock(&(mesh->mesh_mutex));
1741 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1743 meshlink_errno = MESHLINK_EINVAL;
1747 char *address = meshlink_get_external_address(mesh);
1755 pthread_mutex_lock(&(mesh->mesh_mutex));
1756 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1757 pthread_mutex_unlock(&(mesh->mesh_mutex));
1763 int meshlink_get_port(meshlink_handle_t *mesh) {
1765 meshlink_errno = MESHLINK_EINVAL;
1770 meshlink_errno = MESHLINK_EINTERNAL;
1774 return atoi(mesh->myport);
1777 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1778 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1779 meshlink_errno = MESHLINK_EINVAL;
1783 if(mesh->myport && port == atoi(mesh->myport)) {
1787 if(!try_bind(port)) {
1788 meshlink_errno = MESHLINK_ENETWORK;
1794 pthread_mutex_lock(&(mesh->mesh_mutex));
1796 if(mesh->threadstarted) {
1797 meshlink_errno = MESHLINK_EINVAL;
1801 close_network_connections(mesh);
1802 exit_configuration(&mesh->config);
1805 snprintf(portstr, sizeof(portstr), "%d", port);
1806 portstr[sizeof(portstr) - 1] = 0;
1808 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1810 init_configuration(&mesh->config);
1812 if(!read_server_config(mesh)) {
1813 meshlink_errno = MESHLINK_ESTORAGE;
1814 } else if(!setup_network(mesh)) {
1815 meshlink_errno = MESHLINK_ENETWORK;
1821 pthread_mutex_unlock(&(mesh->mesh_mutex));
1826 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1828 meshlink_errno = MESHLINK_EINVAL;
1832 pthread_mutex_lock(&(mesh->mesh_mutex));
1834 // Check validity of the new node's name
1835 if(!check_id(name)) {
1836 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1837 meshlink_errno = MESHLINK_EINVAL;
1838 pthread_mutex_unlock(&(mesh->mesh_mutex));
1842 // Ensure no host configuration file with that name exists
1843 char filename[PATH_MAX];
1844 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1846 if(!access(filename, F_OK)) {
1847 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1848 meshlink_errno = MESHLINK_EEXIST;
1849 pthread_mutex_unlock(&(mesh->mesh_mutex));
1853 // Ensure no other nodes know about this name
1854 if(meshlink_get_node(mesh, name)) {
1855 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1856 meshlink_errno = MESHLINK_EEXIST;
1857 pthread_mutex_unlock(&(mesh->mesh_mutex));
1861 // Get the local address
1862 char *address = get_my_hostname(mesh);
1865 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1866 meshlink_errno = MESHLINK_ERESOLV;
1867 pthread_mutex_unlock(&(mesh->mesh_mutex));
1871 if(!refresh_invitation_key(mesh)) {
1872 meshlink_errno = MESHLINK_EINTERNAL;
1873 pthread_mutex_unlock(&(mesh->mesh_mutex));
1879 // Create a hash of the key.
1880 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1881 sha512(fingerprint, strlen(fingerprint), hash);
1882 b64encode_urlsafe(hash, hash, 18);
1884 // Create a random cookie for this invitation.
1886 randomize(cookie, 18);
1888 // Create a filename that doesn't reveal the cookie itself
1889 char buf[18 + strlen(fingerprint)];
1890 char cookiehash[64];
1891 memcpy(buf, cookie, 18);
1892 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1893 sha512(buf, sizeof(buf), cookiehash);
1894 b64encode_urlsafe(cookiehash, cookiehash, 18);
1896 b64encode_urlsafe(cookie, cookie, 18);
1900 // Create a file containing the details of the invitation.
1901 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1902 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1905 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1906 meshlink_errno = MESHLINK_ESTORAGE;
1907 pthread_mutex_unlock(&(mesh->mesh_mutex));
1911 FILE *f = fdopen(ifd, "w");
1917 // Fill in the details.
1918 fprintf(f, "Name = %s\n", name);
1920 // fprintf(f, "NetName = %s\n", netname);
1921 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1923 // Copy Broadcast and Mode
1924 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1925 FILE *tc = fopen(filename, "r");
1930 while(fgets(buf, sizeof(buf), tc)) {
1931 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1932 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1935 // Make sure there is a newline character.
1936 if(!strchr(buf, '\n')) {
1944 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1945 meshlink_errno = MESHLINK_ESTORAGE;
1946 pthread_mutex_unlock(&(mesh->mesh_mutex));
1950 fprintf(f, "#---------------------------------------------------------------#\n");
1951 fprintf(f, "Name = %s\n", mesh->self->name);
1953 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1957 // Create an URL from the local address, key hash and cookie
1959 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1962 pthread_mutex_unlock(&(mesh->mesh_mutex));
1966 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1967 if(!mesh || !invitation) {
1968 meshlink_errno = MESHLINK_EINVAL;
1972 pthread_mutex_lock(&(mesh->mesh_mutex));
1974 //Before doing meshlink_join make sure we are not connected to another mesh
1975 if(mesh->threadstarted) {
1976 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1977 meshlink_errno = MESHLINK_EINVAL;
1978 pthread_mutex_unlock(&(mesh->mesh_mutex));
1982 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1983 char copy[strlen(invitation) + 1];
1984 strcpy(copy, invitation);
1986 // Split the invitation URL into hostname, port, key hash and cookie.
1988 char *slash = strchr(copy, '/');
1996 if(strlen(slash) != 48) {
2000 char *address = copy;
2001 char *port = strrchr(address, ':');
2009 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2013 // Generate a throw-away key for the invitation.
2014 ecdsa_t *key = ecdsa_generate();
2017 meshlink_errno = MESHLINK_EINTERNAL;
2018 pthread_mutex_unlock(&(mesh->mesh_mutex));
2022 char *b64key = ecdsa_get_base64_public_key(key);
2026 while(address && *address) {
2027 // We allow commas in the address part to support multiple addresses in one invitation URL.
2028 comma = strchr(address, ',');
2034 // IPv6 address are enclosed in brackets, per RFC 3986
2035 if(*address == '[') {
2037 char *bracket = strchr(address, ']');
2045 if(comma && bracket != comma) {
2050 // Connect to the meshlink daemon mentioned in the URL.
2051 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2054 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2055 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2057 if(mesh->sock == -1) {
2058 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2059 meshlink_errno = MESHLINK_ENETWORK;
2063 set_timeout(mesh->sock, 5000);
2065 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2066 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2067 meshlink_errno = MESHLINK_ENETWORK;
2068 closesocket(mesh->sock);
2076 meshlink_errno = MESHLINK_ERESOLV;
2079 if(mesh->sock != -1 || !comma) {
2086 if(mesh->sock == -1) {
2087 pthread_mutex_unlock(&mesh->mesh_mutex);
2091 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2093 // Tell him we have an invitation, and give him our throw-away key.
2097 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
2098 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2099 closesocket(mesh->sock);
2100 meshlink_errno = MESHLINK_ENETWORK;
2101 pthread_mutex_unlock(&(mesh->mesh_mutex));
2107 char hisname[4096] = "";
2108 int code, hismajor, hisminor = 0;
2110 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) {
2111 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2112 closesocket(mesh->sock);
2113 meshlink_errno = MESHLINK_ENETWORK;
2114 pthread_mutex_unlock(&(mesh->mesh_mutex));
2118 // Check if the hash of the key he gave us matches the hash in the URL.
2119 char *fingerprint = mesh->line + 2;
2122 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2123 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2124 meshlink_errno = MESHLINK_EINTERNAL;
2125 pthread_mutex_unlock(&(mesh->mesh_mutex));
2129 if(memcmp(hishash, mesh->hash, 18)) {
2130 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2131 meshlink_errno = MESHLINK_EPEER;
2132 pthread_mutex_unlock(&(mesh->mesh_mutex));
2137 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2140 meshlink_errno = MESHLINK_EINTERNAL;
2141 pthread_mutex_unlock(&(mesh->mesh_mutex));
2145 // Start an SPTPS session
2146 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2147 meshlink_errno = MESHLINK_EINTERNAL;
2148 pthread_mutex_unlock(&(mesh->mesh_mutex));
2152 // Feed rest of input buffer to SPTPS
2153 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2154 meshlink_errno = MESHLINK_EPEER;
2155 pthread_mutex_unlock(&(mesh->mesh_mutex));
2161 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2163 if(errno == EINTR) {
2167 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2168 meshlink_errno = MESHLINK_ENETWORK;
2169 pthread_mutex_unlock(&(mesh->mesh_mutex));
2173 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2174 meshlink_errno = MESHLINK_EPEER;
2175 pthread_mutex_unlock(&(mesh->mesh_mutex));
2180 sptps_stop(&mesh->sptps);
2183 closesocket(mesh->sock);
2185 if(!mesh->success) {
2186 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2187 meshlink_errno = MESHLINK_EPEER;
2188 pthread_mutex_unlock(&(mesh->mesh_mutex));
2192 pthread_mutex_unlock(&(mesh->mesh_mutex));
2196 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2197 meshlink_errno = MESHLINK_EINVAL;
2198 pthread_mutex_unlock(&(mesh->mesh_mutex));
2202 char *meshlink_export(meshlink_handle_t *mesh) {
2204 meshlink_errno = MESHLINK_EINVAL;
2208 pthread_mutex_lock(&(mesh->mesh_mutex));
2210 char filename[PATH_MAX];
2211 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2212 FILE *f = fopen(filename, "r");
2215 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2216 meshlink_errno = MESHLINK_ESTORAGE;
2217 pthread_mutex_unlock(&(mesh->mesh_mutex));
2221 fseek(f, 0, SEEK_END);
2222 int fsize = ftell(f);
2225 size_t len = fsize + 9 + strlen(mesh->self->name);
2226 char *buf = xmalloc(len);
2227 snprintf(buf, len, "Name = %s\n", mesh->self->name);
2229 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2230 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2233 meshlink_errno = MESHLINK_ESTORAGE;
2234 pthread_mutex_unlock(&(mesh->mesh_mutex));
2241 pthread_mutex_unlock(&(mesh->mesh_mutex));
2245 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2246 if(!mesh || !data) {
2247 meshlink_errno = MESHLINK_EINVAL;
2251 pthread_mutex_lock(&(mesh->mesh_mutex));
2253 if(strncmp(data, "Name = ", 7)) {
2254 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2255 meshlink_errno = MESHLINK_EPEER;
2256 pthread_mutex_unlock(&(mesh->mesh_mutex));
2260 char *end = strchr(data + 7, '\n');
2263 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2264 meshlink_errno = MESHLINK_EPEER;
2265 pthread_mutex_unlock(&(mesh->mesh_mutex));
2269 int len = end - (data + 7);
2271 memcpy(name, data + 7, len);
2274 if(!check_id(name)) {
2275 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2276 meshlink_errno = MESHLINK_EPEER;
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2281 char filename[PATH_MAX];
2282 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2284 if(!access(filename, F_OK)) {
2285 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2286 meshlink_errno = MESHLINK_EEXIST;
2287 pthread_mutex_unlock(&(mesh->mesh_mutex));
2291 if(errno != ENOENT) {
2292 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2293 meshlink_errno = MESHLINK_ESTORAGE;
2294 pthread_mutex_unlock(&(mesh->mesh_mutex));
2298 FILE *f = fopen(filename, "w");
2301 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2302 meshlink_errno = MESHLINK_ESTORAGE;
2303 pthread_mutex_unlock(&(mesh->mesh_mutex));
2307 fwrite(end + 1, strlen(end + 1), 1, f);
2310 load_all_nodes(mesh);
2312 pthread_mutex_unlock(&(mesh->mesh_mutex));
2316 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2317 if(!mesh || !node) {
2318 meshlink_errno = MESHLINK_EINVAL;
2322 pthread_mutex_lock(&(mesh->mesh_mutex));
2326 n->status.blacklisted = true;
2327 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2329 //Make blacklisting persistent in the config file
2330 append_config_file(mesh, n->name, "blacklisted", "yes");
2332 pthread_mutex_unlock(&(mesh->mesh_mutex));
2336 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2337 if(!mesh || !node) {
2338 meshlink_errno = MESHLINK_EINVAL;
2342 pthread_mutex_lock(&(mesh->mesh_mutex));
2344 node_t *n = (node_t *)node;
2345 n->status.blacklisted = false;
2347 //TODO: remove blacklisted = yes from the config file
2349 pthread_mutex_unlock(&(mesh->mesh_mutex));
2353 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2354 mesh->default_blacklist = blacklist;
2357 /* Hint that a hostname may be found at an address
2358 * See header file for detailed comment.
2360 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2361 if(!mesh || !node || !addr) {
2365 // Ignore hints about ourself.
2366 if((node_t *)node == mesh->self) {
2370 pthread_mutex_lock(&(mesh->mesh_mutex));
2372 char *host = NULL, *port = NULL, *str = NULL;
2373 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2376 xasprintf(&str, "%s %s", host, port);
2378 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2379 modify_config_file(mesh, node->name, "Address", str, 5);
2381 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2389 pthread_mutex_unlock(&(mesh->mesh_mutex));
2390 // @TODO do we want to fire off a connection attempt right away?
2393 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2395 node_t *n = utcp->priv;
2396 meshlink_handle_t *mesh = n->mesh;
2397 return mesh->channel_accept_cb;
2400 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, 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(n->status.destroyed) {
2411 meshlink_channel_close(mesh, channel);
2412 } else if(channel->receive_cb) {
2413 channel->receive_cb(mesh, channel, data, len);
2419 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2420 node_t *n = utcp_connection->utcp->priv;
2426 meshlink_handle_t *mesh = n->mesh;
2428 if(!mesh->channel_accept_cb) {
2432 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2434 channel->c = utcp_connection;
2436 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2437 utcp_accept(utcp_connection, channel_recv, channel);
2443 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2444 node_t *n = utcp->priv;
2445 meshlink_handle_t *mesh = n->mesh;
2446 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2449 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2450 if(!mesh || !channel) {
2451 meshlink_errno = MESHLINK_EINVAL;
2455 channel->receive_cb = cb;
2458 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2460 node_t *n = (node_t *)source;
2466 utcp_recv(n->utcp, data, len);
2469 static void channel_poll(struct utcp_connection *connection, size_t len) {
2470 meshlink_channel_t *channel = connection->priv;
2476 node_t *n = channel->node;
2477 meshlink_handle_t *mesh = n->mesh;
2479 if(channel->poll_cb) {
2480 channel->poll_cb(mesh, channel, len);
2484 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2486 channel->poll_cb = cb;
2487 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2490 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2492 meshlink_errno = MESHLINK_EINVAL;
2496 pthread_mutex_lock(&mesh->mesh_mutex);
2497 mesh->channel_accept_cb = cb;
2498 mesh->receive_cb = channel_receive;
2500 for splay_each(node_t, n, mesh->nodes) {
2501 if(!n->utcp && n != mesh->self) {
2502 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2506 pthread_mutex_unlock(&mesh->mesh_mutex);
2509 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) {
2511 abort(); // TODO: handle non-NULL data
2514 if(!mesh || !node) {
2515 meshlink_errno = MESHLINK_EINVAL;
2519 node_t *n = (node_t *)node;
2522 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2523 mesh->receive_cb = channel_receive;
2526 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2531 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2533 channel->receive_cb = cb;
2534 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2537 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2545 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) {
2546 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2549 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2550 if(!mesh || !channel) {
2551 meshlink_errno = MESHLINK_EINVAL;
2555 utcp_shutdown(channel->c, direction);
2558 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2559 if(!mesh || !channel) {
2560 meshlink_errno = MESHLINK_EINVAL;
2564 utcp_close(channel->c);
2568 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2569 if(!mesh || !channel) {
2570 meshlink_errno = MESHLINK_EINVAL;
2579 meshlink_errno = MESHLINK_EINVAL;
2583 // TODO: more finegrained locking.
2584 // Ideally we want to put the data into the UTCP connection's send buffer.
2585 // Then, preferrably only if there is room in the receiver window,
2586 // kick the meshlink thread to go send packets.
2588 pthread_mutex_lock(&mesh->mesh_mutex);
2589 ssize_t retval = utcp_send(channel->c, data, len);
2590 pthread_mutex_unlock(&mesh->mesh_mutex);
2593 meshlink_errno = MESHLINK_ENETWORK;
2599 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2600 if(!mesh || !channel) {
2601 meshlink_errno = MESHLINK_EINVAL;
2605 return channel->c->flags;
2608 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2609 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2610 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2613 if(mesh->node_status_cb) {
2614 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2618 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2620 meshlink_errno = MESHLINK_EINVAL;
2624 pthread_mutex_lock(&mesh->mesh_mutex);
2626 if(mesh->discovery == enable) {
2630 if(mesh->threadstarted) {
2632 discovery_start(mesh);
2634 discovery_stop(mesh);
2638 mesh->discovery = enable;
2641 pthread_mutex_unlock(&mesh->mesh_mutex);
2644 static void __attribute__((constructor)) meshlink_init(void) {
2647 randomize(&seed, sizeof(seed));
2651 static void __attribute__((destructor)) meshlink_exit(void) {
2655 /// Device class traits
2656 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2657 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2658 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2659 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2660 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN