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");
123 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
129 while((len = fread(buf, 1, sizeof(buf), in)))
130 fwrite(buf, len, 1, out);
135 static int rstrip(char *value) {
136 int len = strlen(value);
137 while(len && strchr("\t\r\n ", value[len - 1]))
142 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
144 if(!filename || (*hostname && *port))
147 FILE *f = fopen(filename, "r");
151 while(fgets(line, sizeof(line), f)) {
155 p += strcspn(p, "\t =");
158 q = p + strspn(p, "\t ");
160 q += 1 + strspn(q + 1, "\t ");
162 p = q + strcspn(q, "\t ");
165 p += strspn(p, "\t ");
166 p[strcspn(p, "\t ")] = 0;
168 if(!*port && !strcasecmp(line, "Port"))
170 else if(!*hostname && !strcasecmp(line, "Address")) {
171 *hostname = xstrdup(q);
178 if(*hostname && *port)
185 static bool is_valid_hostname(const char *hostname) {
186 for(const char *p = hostname; *p; p++) {
187 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':'))
194 static void set_timeout(int sock, int timeout) {
199 tv.tv_sec = timeout / 1000;
200 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
202 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
203 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
206 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
207 char *hostname = NULL;
209 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
210 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
211 struct addrinfo *aip = ai;
212 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
216 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
218 set_timeout(s, 5000);
219 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
225 send(s, request, sizeof(request) - 1, 0);
226 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
229 if(line[len - 1] == '\n')
231 char *p = strrchr(line, '\n');
233 hostname = xstrdup(p + 1);
246 // Check that the hostname is reasonable
247 if(hostname && !is_valid_hostname(hostname)) {
253 meshlink_errno = MESHLINK_ERESOLV;
258 static char *get_my_hostname(meshlink_handle_t *mesh) {
259 char *hostname = NULL;
261 char *hostport = NULL;
262 char *name = mesh->self->name;
263 char filename[PATH_MAX] = "";
266 // Use first Address statement in own host config file
267 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
268 scan_for_hostname(filename, &hostname, &port);
273 hostname = meshlink_get_external_address(mesh);
277 f = fopen(filename, "a");
279 fprintf(f, "\nAddress = %s\n", hostname);
282 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
286 if(strchr(hostname, ':'))
287 xasprintf(&hostport, "[%s]:%s", hostname, port);
289 xasprintf(&hostport, "%s:%s", hostname, port);
291 if(strchr(hostname, ':'))
292 xasprintf(&hostport, "[%s]", hostname);
294 hostport = xstrdup(hostname);
302 static char *get_line(const char **data) {
311 static char line[1024];
312 const char *end = strchr(*data, '\n');
313 size_t len = end ? end - *data : strlen(*data);
314 if(len >= sizeof(line)) {
315 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
318 if(len && !isprint(**data))
321 memcpy(line, *data, len);
332 static char *get_value(const char *data, const char *var) {
333 char *line = get_line(&data);
337 char *sep = line + strcspn(line, " \t=");
338 char *val = sep + strspn(sep, " \t");
340 val += 1 + strspn(val + 1, " \t");
342 if(strcasecmp(line, var))
347 static bool try_bind(int port) {
348 struct addrinfo *ai = NULL;
349 struct addrinfo hint = {
350 .ai_flags = AI_PASSIVE,
351 .ai_family = AF_UNSPEC,
352 .ai_socktype = SOCK_STREAM,
353 .ai_protocol = IPPROTO_TCP,
357 snprintf(portstr, sizeof(portstr), "%d", port);
359 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
363 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
368 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
381 static int check_port(meshlink_handle_t *mesh) {
382 for(int i = 0; i < 1000; i++) {
383 int port = 0x1000 + (rand() & 0x7fff);
385 char filename[PATH_MAX];
386 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
387 FILE *f = fopen(filename, "a");
389 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
393 fprintf(f, "Port = %d\n", port);
399 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
403 static bool finalize_join(meshlink_handle_t *mesh) {
404 char *name = xstrdup(get_value(mesh->data, "Name"));
406 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
410 if(!check_id(name)) {
411 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
415 char filename[PATH_MAX];
416 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
418 FILE *f = fopen(filename, "w");
420 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
424 fprintf(f, "Name = %s\n", name);
426 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
427 FILE *fh = fopen(filename, "w");
429 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
434 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
435 // Other chunks go unfiltered to their respective host config files
436 const char *p = mesh->data;
439 while((l = get_line(&p))) {
444 // Split line into variable and value
445 int len = strcspn(l, "\t =");
447 value += strspn(value, "\t ");
450 value += strspn(value, "\t ");
455 if(!strcasecmp(l, "Name"))
456 if(strcmp(value, name))
460 else if(!strcasecmp(l, "NetName"))
463 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
466 for(i = 0; variables[i].name; i++) {
467 if(strcasecmp(l, variables[i].name))
473 // Ignore unknown and unsafe variables
475 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
477 } else if(!(variables[i].type & VAR_SAFE)) {
478 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
482 // Copy the safe variable to the right config file
483 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
488 while(l && !strcasecmp(l, "Name")) {
489 if(!check_id(value)) {
490 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
494 if(!strcmp(value, name)) {
495 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
499 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
500 f = fopen(filename, "w");
503 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
507 while((l = get_line(&p))) {
508 if(!strcmp(l, "#---------------------------------------------------------------#"))
510 int len = strcspn(l, "\t =");
511 if(len == 4 && !strncasecmp(l, "Name", 4)) {
513 value += strspn(value, "\t ");
516 value += strspn(value, "\t ");
529 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
535 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
536 fprintf(fh, "Port = %s\n", mesh->myport);
540 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
543 free(mesh->self->name);
544 free(mesh->self->connection->name);
545 mesh->self->name = xstrdup(name);
546 mesh->self->connection->name = name;
548 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
550 load_all_nodes(mesh);
555 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
556 meshlink_handle_t *mesh = handle;
558 int result = send(mesh->sock, data, len, 0);
559 if(result == -1 && errno == EINTR)
569 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
570 meshlink_handle_t *mesh = handle;
572 case SPTPS_HANDSHAKE:
573 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
576 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
577 memcpy(mesh->data + mesh->thedatalen, msg, len);
578 mesh->thedatalen += len;
579 mesh->data[mesh->thedatalen] = 0;
583 mesh->thedatalen = 0;
584 return finalize_join(mesh);
587 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
588 shutdown(mesh->sock, SHUT_RDWR);
589 mesh->success = true;
599 static bool recvline(meshlink_handle_t *mesh, size_t len) {
600 char *newline = NULL;
605 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
606 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
607 if(result == -1 && errno == EINTR)
611 mesh->blen += result;
614 if(newline - mesh->buffer >= len)
617 len = newline - mesh->buffer;
619 memcpy(mesh->line, mesh->buffer, len);
621 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
622 mesh->blen -= len + 1;
626 static bool sendline(int fd, char *format, ...) {
627 static char buffer[4096];
632 va_start(ap, format);
633 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
636 if(blen < 1 || blen >= sizeof(buffer))
643 int result = send(fd, p, blen, MSG_NOSIGNAL);
644 if(result == -1 && errno == EINTR)
655 static const char *errstr[] = {
656 [MESHLINK_OK] = "No error",
657 [MESHLINK_EINVAL] = "Invalid argument",
658 [MESHLINK_ENOMEM] = "Out of memory",
659 [MESHLINK_ENOENT] = "No such node",
660 [MESHLINK_EEXIST] = "Node already exists",
661 [MESHLINK_EINTERNAL] = "Internal error",
662 [MESHLINK_ERESOLV] = "Could not resolve hostname",
663 [MESHLINK_ESTORAGE] = "Storage error",
664 [MESHLINK_ENETWORK] = "Network error",
665 [MESHLINK_EPEER] = "Error communicating with peer",
668 const char *meshlink_strerror(meshlink_errno_t err) {
669 if(err < 0 || err >= sizeof(errstr) / sizeof(*errstr))
670 return "Invalid error code";
674 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
677 char pubname[PATH_MAX], privname[PATH_MAX];
679 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
681 if(!(key = ecdsa_generate())) {
682 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
683 meshlink_errno = MESHLINK_EINTERNAL;
686 logger(mesh, MESHLINK_DEBUG, "Done.\n");
688 snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase);
689 f = fopen(privname, "wb");
692 meshlink_errno = MESHLINK_ESTORAGE;
697 fchmod(fileno(f), 0600);
700 if(!ecdsa_write_pem_private_key(key, f)) {
701 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
704 meshlink_errno = MESHLINK_EINTERNAL;
710 snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
711 f = fopen(pubname, "a");
714 meshlink_errno = MESHLINK_ESTORAGE;
718 char *pubkey = ecdsa_get_base64_public_key(key);
719 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
728 static struct timeval idle(event_loop_t *loop, void *data) {
729 meshlink_handle_t *mesh = data;
730 struct timeval t, tmin = {3600, 0};
731 for splay_each(node_t, n, mesh->nodes) {
734 t = utcp_timeout(n->utcp);
735 if(timercmp(&t, &tmin, <))
741 // Find out what local address a socket would use if we connect to the given address.
742 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
743 // of both endpoints, but this will actually not send any UDP packet.
744 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
745 struct addrinfo *rai = NULL;
746 const struct addrinfo hint = {
747 .ai_family = AF_UNSPEC,
748 .ai_socktype = SOCK_DGRAM,
749 .ai_protocol = IPPROTO_UDP,
752 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
755 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
761 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
768 struct sockaddr_storage sn;
769 socklen_t sl = sizeof(sn);
771 if(getsockname(sock, (struct sockaddr *)&sn, &sl))
774 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
780 // Get our local address(es) by simulating connecting to an Internet host.
781 static void add_local_addresses(meshlink_handle_t *mesh) {
782 char host[NI_MAXHOST];
783 char entry[MAX_STRING_SIZE];
787 if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
788 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
789 append_config_file(mesh, mesh->name, "Address", entry);
794 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
795 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
796 append_config_file(mesh, mesh->name, "Address", entry);
800 static bool meshlink_setup(meshlink_handle_t *mesh) {
801 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
802 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
803 meshlink_errno = MESHLINK_ESTORAGE;
807 char filename[PATH_MAX];
808 snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
810 if(mkdir(filename, 0777) && errno != EEXIST) {
811 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
812 meshlink_errno = MESHLINK_ESTORAGE;
816 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
818 if(!access(filename, F_OK)) {
819 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
820 meshlink_errno = MESHLINK_EEXIST;
824 FILE *f = fopen(filename, "w");
826 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
827 meshlink_errno = MESHLINK_ESTORAGE;
831 fprintf(f, "Name = %s\n", mesh->name);
834 if(!ecdsa_keygen(mesh)) {
835 meshlink_errno = MESHLINK_EINTERNAL;
844 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
845 // Validate arguments provided by the application
846 bool usingname = false;
848 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
850 if(!confbase || !*confbase) {
851 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
852 meshlink_errno = MESHLINK_EINVAL;
856 if(!appname || !*appname) {
857 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
858 meshlink_errno = MESHLINK_EINVAL;
862 if(!name || !*name) {
863 logger(NULL, MESHLINK_ERROR, "No name given!\n");
865 } else { //check name only if there is a name != NULL
867 if(!check_id(name)) {
868 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
869 meshlink_errno = MESHLINK_EINVAL;
875 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
876 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
877 meshlink_errno = MESHLINK_EINVAL;
881 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
882 mesh->confbase = xstrdup(confbase);
883 mesh->appname = xstrdup(appname);
884 mesh->devclass = devclass;
885 if(usingname) mesh->name = xstrdup(name);
888 pthread_mutexattr_t attr;
889 pthread_mutexattr_init(&attr);
890 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
891 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
893 mesh->threadstarted = false;
894 event_loop_init(&mesh->loop);
895 mesh->loop.data = mesh;
897 // Check whether meshlink.conf already exists
899 char filename[PATH_MAX];
900 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
902 if(access(filename, R_OK)) {
903 if(errno == ENOENT) {
905 if(!meshlink_setup(mesh)) {
906 // meshlink_errno is set by meshlink_setup()
910 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
911 meshlink_close(mesh);
912 meshlink_errno = MESHLINK_ESTORAGE;
917 // Read the configuration
919 init_configuration(&mesh->config);
921 if(!read_server_config(mesh)) {
922 meshlink_close(mesh);
923 meshlink_errno = MESHLINK_ESTORAGE;
928 struct WSAData wsa_state;
929 WSAStartup(MAKEWORD(2, 2), &wsa_state);
932 // Setup up everything
933 // TODO: we should not open listening sockets yet
935 if(!setup_network(mesh)) {
936 meshlink_close(mesh);
937 meshlink_errno = MESHLINK_ENETWORK;
941 add_local_addresses(mesh);
943 idle_set(&mesh->loop, idle, mesh);
945 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
949 static void *meshlink_main_loop(void *arg) {
950 meshlink_handle_t *mesh = arg;
952 pthread_mutex_lock(&(mesh->mesh_mutex));
954 try_outgoing_connections(mesh);
956 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
958 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
960 pthread_mutex_unlock(&(mesh->mesh_mutex));
964 bool meshlink_start(meshlink_handle_t *mesh) {
966 meshlink_errno = MESHLINK_EINVAL;
970 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
972 pthread_mutex_lock(&(mesh->mesh_mutex));
974 if(mesh->threadstarted) {
975 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
976 pthread_mutex_unlock(&(mesh->mesh_mutex));
980 if(mesh->listen_socket[0].tcp.fd < 0) {
981 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
982 meshlink_errno = MESHLINK_ENETWORK;
986 mesh->thedatalen = 0;
988 // TODO: open listening sockets first
990 //Check that a valid name is set
992 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
993 meshlink_errno = MESHLINK_EINVAL;
994 pthread_mutex_unlock(&(mesh->mesh_mutex));
998 // Start the main thread
1000 event_loop_start(&mesh->loop);
1002 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1003 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1004 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1005 meshlink_errno = MESHLINK_EINTERNAL;
1006 pthread_mutex_unlock(&(mesh->mesh_mutex));
1010 mesh->threadstarted = true;
1013 discovery_start(mesh);
1015 pthread_mutex_unlock(&(mesh->mesh_mutex));
1019 void meshlink_stop(meshlink_handle_t *mesh) {
1021 meshlink_errno = MESHLINK_EINVAL;
1025 pthread_mutex_lock(&(mesh->mesh_mutex));
1026 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1030 discovery_stop(mesh);
1032 // Shut down the main thread
1033 event_loop_stop(&mesh->loop);
1035 // Send ourselves a UDP packet to kick the event loop
1036 listen_socket_t *s = &mesh->listen_socket[0];
1037 if(sendto(s->udp.fd, "", 1, MSG_NOSIGNAL, &s->sa.sa, SALEN(s->sa.sa)) == -1)
1038 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself");
1040 // Wait for the main thread to finish
1041 pthread_mutex_unlock(&(mesh->mesh_mutex));
1042 pthread_join(mesh->thread, NULL);
1043 pthread_mutex_lock(&(mesh->mesh_mutex));
1045 mesh->threadstarted = false;
1047 pthread_mutex_unlock(&(mesh->mesh_mutex));
1050 void meshlink_close(meshlink_handle_t *mesh) {
1051 if(!mesh || !mesh->confbase) {
1052 meshlink_errno = MESHLINK_EINVAL;
1056 // stop can be called even if mesh has not been started
1057 meshlink_stop(mesh);
1059 // lock is not released after this
1060 pthread_mutex_lock(&(mesh->mesh_mutex));
1062 // Close and free all resources used.
1064 close_network_connections(mesh);
1066 logger(mesh, MESHLINK_INFO, "Terminating");
1068 exit_configuration(&mesh->config);
1069 event_loop_exit(&mesh->loop);
1076 ecdsa_free(mesh->invitation_key);
1079 free(mesh->appname);
1080 free(mesh->confbase);
1081 pthread_mutex_destroy(&(mesh->mesh_mutex));
1083 memset(mesh, 0, sizeof(*mesh));
1088 static void deltree(const char *dirname) {
1089 DIR *d = opendir(dirname);
1092 while((ent = readdir(d))) {
1093 if(ent->d_name[0] == '.')
1095 char filename[PATH_MAX];
1096 snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
1097 if(unlink(filename))
1106 bool meshlink_destroy(const char *confbase) {
1108 meshlink_errno = MESHLINK_EINVAL;
1112 char filename[PATH_MAX];
1113 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1115 if(unlink(filename)) {
1116 if(errno == ENOENT) {
1117 meshlink_errno = MESHLINK_ENOENT;
1120 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1121 meshlink_errno = MESHLINK_ESTORAGE;
1131 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1133 meshlink_errno = MESHLINK_EINVAL;
1137 pthread_mutex_lock(&(mesh->mesh_mutex));
1138 mesh->receive_cb = cb;
1139 pthread_mutex_unlock(&(mesh->mesh_mutex));
1142 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1144 meshlink_errno = MESHLINK_EINVAL;
1148 pthread_mutex_lock(&(mesh->mesh_mutex));
1149 mesh->node_status_cb = cb;
1150 pthread_mutex_unlock(&(mesh->mesh_mutex));
1153 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1155 pthread_mutex_lock(&(mesh->mesh_mutex));
1157 mesh->log_level = cb ? level : 0;
1158 pthread_mutex_unlock(&(mesh->mesh_mutex));
1161 global_log_level = cb ? level : 0;
1165 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1166 meshlink_packethdr_t *hdr;
1168 // Validate arguments
1169 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1170 meshlink_errno = MESHLINK_EINVAL;
1178 meshlink_errno = MESHLINK_EINVAL;
1182 // Prepare the packet
1183 vpn_packet_t *packet = malloc(sizeof(*packet));
1185 meshlink_errno = MESHLINK_ENOMEM;
1189 packet->probe = false;
1190 packet->tcp = false;
1191 packet->len = len + sizeof(*hdr);
1193 hdr = (meshlink_packethdr_t *)packet->data;
1194 memset(hdr, 0, sizeof(*hdr));
1195 // leave the last byte as 0 to make sure strings are always
1196 // null-terminated if they are longer than the buffer
1197 strncpy(hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1198 strncpy(hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1200 memcpy(packet->data + sizeof(*hdr), data, len);
1203 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1205 meshlink_errno = MESHLINK_ENOMEM;
1209 // Notify event loop
1210 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1215 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1216 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1220 mesh->self->in_packets++;
1221 mesh->self->in_bytes += packet->len;
1222 route(mesh, mesh->self, packet);
1225 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1226 if(!mesh || !destination) {
1227 meshlink_errno = MESHLINK_EINVAL;
1230 pthread_mutex_lock(&(mesh->mesh_mutex));
1232 node_t *n = (node_t *)destination;
1233 if(!n->status.reachable) {
1234 pthread_mutex_unlock(&(mesh->mesh_mutex));
1237 } else if(n->mtuprobes > 30 && n->minmtu) {
1238 pthread_mutex_unlock(&(mesh->mesh_mutex));
1241 pthread_mutex_unlock(&(mesh->mesh_mutex));
1246 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1247 if(!mesh || !node) {
1248 meshlink_errno = MESHLINK_EINVAL;
1251 pthread_mutex_lock(&(mesh->mesh_mutex));
1253 node_t *n = (node_t *)node;
1255 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1256 meshlink_errno = MESHLINK_EINTERNAL;
1257 pthread_mutex_unlock(&(mesh->mesh_mutex));
1261 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1264 meshlink_errno = MESHLINK_EINTERNAL;
1266 pthread_mutex_unlock(&(mesh->mesh_mutex));
1270 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1272 meshlink_errno = MESHLINK_EINVAL;
1276 return (meshlink_node_t *)mesh->self;
1279 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1280 if(!mesh || !name) {
1281 meshlink_errno = MESHLINK_EINVAL;
1285 meshlink_node_t *node = NULL;
1287 pthread_mutex_lock(&(mesh->mesh_mutex));
1288 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1289 pthread_mutex_unlock(&(mesh->mesh_mutex));
1293 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1294 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1295 meshlink_errno = MESHLINK_EINVAL;
1299 meshlink_node_t **result;
1302 pthread_mutex_lock(&(mesh->mesh_mutex));
1304 *nmemb = mesh->nodes->count;
1305 result = realloc(nodes, *nmemb * sizeof(*nodes));
1308 meshlink_node_t **p = result;
1309 for splay_each(node_t, n, mesh->nodes)
1310 *p++ = (meshlink_node_t *)n;
1314 meshlink_errno = MESHLINK_ENOMEM;
1317 pthread_mutex_unlock(&(mesh->mesh_mutex));
1322 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1323 if(!mesh || !data || !len || !signature || !siglen) {
1324 meshlink_errno = MESHLINK_EINVAL;
1328 if(*siglen < MESHLINK_SIGLEN) {
1329 meshlink_errno = MESHLINK_EINVAL;
1333 pthread_mutex_lock(&(mesh->mesh_mutex));
1335 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1336 meshlink_errno = MESHLINK_EINTERNAL;
1337 pthread_mutex_unlock(&(mesh->mesh_mutex));
1341 *siglen = MESHLINK_SIGLEN;
1342 pthread_mutex_unlock(&(mesh->mesh_mutex));
1346 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1347 if(!mesh || !data || !len || !signature) {
1348 meshlink_errno = MESHLINK_EINVAL;
1352 if(siglen != MESHLINK_SIGLEN) {
1353 meshlink_errno = MESHLINK_EINVAL;
1357 pthread_mutex_lock(&(mesh->mesh_mutex));
1361 struct node_t *n = (struct node_t *)source;
1362 node_read_ecdsa_public_key(mesh, n);
1364 meshlink_errno = MESHLINK_EINTERNAL;
1367 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1368 pthread_mutex_unlock(&(mesh->mesh_mutex));
1372 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1373 char filename[PATH_MAX];
1375 pthread_mutex_lock(&(mesh->mesh_mutex));
1377 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1378 if(mkdir(filename, 0700) && errno != EEXIST) {
1379 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1380 meshlink_errno = MESHLINK_ESTORAGE;
1381 pthread_mutex_unlock(&(mesh->mesh_mutex));
1385 // Count the number of valid invitations, clean up old ones
1386 DIR *dir = opendir(filename);
1388 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1389 meshlink_errno = MESHLINK_ESTORAGE;
1390 pthread_mutex_unlock(&(mesh->mesh_mutex));
1397 time_t deadline = time(NULL) - 604800; // 1 week in the past
1399 while((ent = readdir(dir))) {
1400 if(strlen(ent->d_name) != 24)
1402 char invname[PATH_MAX];
1404 snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name);
1405 if(!stat(invname, &st)) {
1406 if(mesh->invitation_key && deadline < st.st_mtime)
1411 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1417 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1419 meshlink_errno = MESHLINK_ESTORAGE;
1420 pthread_mutex_unlock(&(mesh->mesh_mutex));
1426 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1428 // Remove the key if there are no outstanding invitations.
1431 if(mesh->invitation_key) {
1432 ecdsa_free(mesh->invitation_key);
1433 mesh->invitation_key = NULL;
1437 if(mesh->invitation_key) {
1438 pthread_mutex_unlock(&(mesh->mesh_mutex));
1442 // Create a new key if necessary.
1443 FILE *f = fopen(filename, "rb");
1445 if(errno != ENOENT) {
1446 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1447 meshlink_errno = MESHLINK_ESTORAGE;
1448 pthread_mutex_unlock(&(mesh->mesh_mutex));
1452 mesh->invitation_key = ecdsa_generate();
1453 if(!mesh->invitation_key) {
1454 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1455 meshlink_errno = MESHLINK_EINTERNAL;
1456 pthread_mutex_unlock(&(mesh->mesh_mutex));
1459 f = fopen(filename, "wb");
1461 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1462 meshlink_errno = MESHLINK_ESTORAGE;
1463 pthread_mutex_unlock(&(mesh->mesh_mutex));
1466 chmod(filename, 0600);
1467 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1470 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1472 if(!mesh->invitation_key) {
1473 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1474 meshlink_errno = MESHLINK_ESTORAGE;
1478 pthread_mutex_unlock(&(mesh->mesh_mutex));
1479 return mesh->invitation_key;
1482 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1483 if(!mesh || !address) {
1484 meshlink_errno = MESHLINK_EINVAL;
1488 if(!is_valid_hostname(address)) {
1489 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1490 meshlink_errno = MESHLINK_EINVAL;
1496 pthread_mutex_lock(&(mesh->mesh_mutex));
1497 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1498 pthread_mutex_unlock(&(mesh->mesh_mutex));
1503 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1505 meshlink_errno = MESHLINK_EINVAL;
1509 char *address = meshlink_get_external_address(mesh);
1515 pthread_mutex_lock(&(mesh->mesh_mutex));
1516 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1517 pthread_mutex_unlock(&(mesh->mesh_mutex));
1523 int meshlink_get_port(meshlink_handle_t *mesh) {
1525 meshlink_errno = MESHLINK_EINVAL;
1530 meshlink_errno = MESHLINK_EINTERNAL;
1534 return atoi(mesh->myport);
1537 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1538 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1539 meshlink_errno = MESHLINK_EINVAL;
1543 if(mesh->myport && port == atoi(mesh->myport))
1546 if(!try_bind(port)) {
1547 meshlink_errno = MESHLINK_ENETWORK;
1553 pthread_mutex_lock(&(mesh->mesh_mutex));
1554 if(mesh->threadstarted) {
1555 meshlink_errno = MESHLINK_EINVAL;
1559 close_network_connections(mesh);
1560 exit_configuration(&mesh->config);
1563 snprintf(portstr, sizeof(portstr), "%d", port);
1564 portstr[sizeof(portstr) - 1] = 0;
1566 modify_config_file(mesh, mesh->name, "Port", portstr, true);
1568 init_configuration(&mesh->config);
1570 if(!read_server_config(mesh))
1571 meshlink_errno = MESHLINK_ESTORAGE;
1572 else if(!setup_network(mesh))
1573 meshlink_errno = MESHLINK_ENETWORK;
1578 pthread_mutex_unlock(&(mesh->mesh_mutex));
1583 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1585 meshlink_errno = MESHLINK_EINVAL;
1589 pthread_mutex_lock(&(mesh->mesh_mutex));
1591 // Check validity of the new node's name
1592 if(!check_id(name)) {
1593 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1594 meshlink_errno = MESHLINK_EINVAL;
1595 pthread_mutex_unlock(&(mesh->mesh_mutex));
1599 // Ensure no host configuration file with that name exists
1600 char filename[PATH_MAX];
1601 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1602 if(!access(filename, F_OK)) {
1603 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1604 meshlink_errno = MESHLINK_EEXIST;
1605 pthread_mutex_unlock(&(mesh->mesh_mutex));
1609 // Ensure no other nodes know about this name
1610 if(meshlink_get_node(mesh, name)) {
1611 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1612 meshlink_errno = MESHLINK_EEXIST;
1613 pthread_mutex_unlock(&(mesh->mesh_mutex));
1617 // Get the local address
1618 char *address = get_my_hostname(mesh);
1620 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1621 meshlink_errno = MESHLINK_ERESOLV;
1622 pthread_mutex_unlock(&(mesh->mesh_mutex));
1626 if(!refresh_invitation_key(mesh)) {
1627 meshlink_errno = MESHLINK_EINTERNAL;
1628 pthread_mutex_unlock(&(mesh->mesh_mutex));
1634 // Create a hash of the key.
1635 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1636 sha512(fingerprint, strlen(fingerprint), hash);
1637 b64encode_urlsafe(hash, hash, 18);
1639 // Create a random cookie for this invitation.
1641 randomize(cookie, 18);
1643 // Create a filename that doesn't reveal the cookie itself
1644 char buf[18 + strlen(fingerprint)];
1645 char cookiehash[64];
1646 memcpy(buf, cookie, 18);
1647 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1648 sha512(buf, sizeof(buf), cookiehash);
1649 b64encode_urlsafe(cookiehash, cookiehash, 18);
1651 b64encode_urlsafe(cookie, cookie, 18);
1655 // Create a file containing the details of the invitation.
1656 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1657 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1659 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1660 meshlink_errno = MESHLINK_ESTORAGE;
1661 pthread_mutex_unlock(&(mesh->mesh_mutex));
1664 FILE *f = fdopen(ifd, "w");
1668 // Fill in the details.
1669 fprintf(f, "Name = %s\n", name);
1671 // fprintf(f, "NetName = %s\n", netname);
1672 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1674 // Copy Broadcast and Mode
1675 snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1676 FILE *tc = fopen(filename, "r");
1679 while(fgets(buf, sizeof(buf), tc)) {
1680 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1681 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1683 // Make sure there is a newline character.
1684 if(!strchr(buf, '\n'))
1690 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1691 meshlink_errno = MESHLINK_ESTORAGE;
1692 pthread_mutex_unlock(&(mesh->mesh_mutex));
1696 fprintf(f, "#---------------------------------------------------------------#\n");
1697 fprintf(f, "Name = %s\n", mesh->self->name);
1699 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1703 // Create an URL from the local address, key hash and cookie
1705 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1708 pthread_mutex_unlock(&(mesh->mesh_mutex));
1712 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1713 if(!mesh || !invitation) {
1714 meshlink_errno = MESHLINK_EINVAL;
1718 pthread_mutex_lock(&(mesh->mesh_mutex));
1720 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1721 char copy[strlen(invitation) + 1];
1722 strcpy(copy, invitation);
1724 // Split the invitation URL into hostname, port, key hash and cookie.
1726 char *slash = strchr(copy, '/');
1732 if(strlen(slash) != 48)
1735 char *address = copy;
1737 if(*address == '[') {
1739 char *bracket = strchr(address, ']');
1743 if(bracket[1] == ':')
1746 port = strchr(address, ':');
1754 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1757 // Generate a throw-away key for the invitation.
1758 ecdsa_t *key = ecdsa_generate();
1760 meshlink_errno = MESHLINK_EINTERNAL;
1761 pthread_mutex_unlock(&(mesh->mesh_mutex));
1765 char *b64key = ecdsa_get_base64_public_key(key);
1767 //Before doing meshlink_join make sure we are not connected to another mesh
1768 if(mesh->threadstarted)
1771 // Connect to the meshlink daemon mentioned in the URL.
1772 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1774 meshlink_errno = MESHLINK_ERESOLV;
1775 pthread_mutex_unlock(&(mesh->mesh_mutex));
1779 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1780 if(mesh->sock <= 0) {
1781 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1783 meshlink_errno = MESHLINK_ENETWORK;
1784 pthread_mutex_unlock(&(mesh->mesh_mutex));
1788 set_timeout(mesh->sock, 5000);
1790 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1791 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1792 closesocket(mesh->sock);
1794 meshlink_errno = MESHLINK_ENETWORK;
1795 pthread_mutex_unlock(&(mesh->mesh_mutex));
1801 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1803 // Tell him we have an invitation, and give him our throw-away key.
1807 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1808 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1809 closesocket(mesh->sock);
1810 meshlink_errno = MESHLINK_ENETWORK;
1811 pthread_mutex_unlock(&(mesh->mesh_mutex));
1817 char hisname[4096] = "";
1818 int code, hismajor, hisminor = 0;
1820 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) {
1821 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1822 closesocket(mesh->sock);
1823 meshlink_errno = MESHLINK_ENETWORK;
1824 pthread_mutex_unlock(&(mesh->mesh_mutex));
1828 // Check if the hash of the key he gave us matches the hash in the URL.
1829 char *fingerprint = mesh->line + 2;
1831 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1832 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1833 meshlink_errno = MESHLINK_EINTERNAL;
1834 pthread_mutex_unlock(&(mesh->mesh_mutex));
1837 if(memcmp(hishash, mesh->hash, 18)) {
1838 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1839 meshlink_errno = MESHLINK_EPEER;
1840 pthread_mutex_unlock(&(mesh->mesh_mutex));
1845 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1847 meshlink_errno = MESHLINK_EINTERNAL;
1848 pthread_mutex_unlock(&(mesh->mesh_mutex));
1852 // Start an SPTPS session
1853 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1854 meshlink_errno = MESHLINK_EINTERNAL;
1855 pthread_mutex_unlock(&(mesh->mesh_mutex));
1859 // Feed rest of input buffer to SPTPS
1860 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1861 meshlink_errno = MESHLINK_EPEER;
1862 pthread_mutex_unlock(&(mesh->mesh_mutex));
1868 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
1872 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1873 meshlink_errno = MESHLINK_ENETWORK;
1874 pthread_mutex_unlock(&(mesh->mesh_mutex));
1878 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1879 meshlink_errno = MESHLINK_EPEER;
1880 pthread_mutex_unlock(&(mesh->mesh_mutex));
1885 sptps_stop(&mesh->sptps);
1888 closesocket(mesh->sock);
1890 if(!mesh->success) {
1891 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1892 meshlink_errno = MESHLINK_EPEER;
1893 pthread_mutex_unlock(&(mesh->mesh_mutex));
1897 pthread_mutex_unlock(&(mesh->mesh_mutex));
1901 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1902 meshlink_errno = MESHLINK_EINVAL;
1903 pthread_mutex_unlock(&(mesh->mesh_mutex));
1907 char *meshlink_export(meshlink_handle_t *mesh) {
1909 meshlink_errno = MESHLINK_EINVAL;
1913 pthread_mutex_lock(&(mesh->mesh_mutex));
1915 char filename[PATH_MAX];
1916 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1917 FILE *f = fopen(filename, "r");
1919 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1920 meshlink_errno = MESHLINK_ESTORAGE;
1921 pthread_mutex_unlock(&(mesh->mesh_mutex));
1925 fseek(f, 0, SEEK_END);
1926 int fsize = ftell(f);
1929 size_t len = fsize + 9 + strlen(mesh->self->name);
1930 char *buf = xmalloc(len);
1931 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1932 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1933 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1935 meshlink_errno = MESHLINK_ESTORAGE;
1936 pthread_mutex_unlock(&(mesh->mesh_mutex));
1943 pthread_mutex_unlock(&(mesh->mesh_mutex));
1947 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1948 if(!mesh || !data) {
1949 meshlink_errno = MESHLINK_EINVAL;
1953 pthread_mutex_lock(&(mesh->mesh_mutex));
1955 if(strncmp(data, "Name = ", 7)) {
1956 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1957 meshlink_errno = MESHLINK_EPEER;
1958 pthread_mutex_unlock(&(mesh->mesh_mutex));
1962 char *end = strchr(data + 7, '\n');
1964 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1965 meshlink_errno = MESHLINK_EPEER;
1966 pthread_mutex_unlock(&(mesh->mesh_mutex));
1970 int len = end - (data + 7);
1972 memcpy(name, data + 7, len);
1974 if(!check_id(name)) {
1975 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1976 meshlink_errno = MESHLINK_EPEER;
1977 pthread_mutex_unlock(&(mesh->mesh_mutex));
1981 char filename[PATH_MAX];
1982 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1983 if(!access(filename, F_OK)) {
1984 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1985 meshlink_errno = MESHLINK_EEXIST;
1986 pthread_mutex_unlock(&(mesh->mesh_mutex));
1990 if(errno != ENOENT) {
1991 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1992 meshlink_errno = MESHLINK_ESTORAGE;
1993 pthread_mutex_unlock(&(mesh->mesh_mutex));
1997 FILE *f = fopen(filename, "w");
1999 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2000 meshlink_errno = MESHLINK_ESTORAGE;
2001 pthread_mutex_unlock(&(mesh->mesh_mutex));
2005 fwrite(end + 1, strlen(end + 1), 1, f);
2008 load_all_nodes(mesh);
2010 pthread_mutex_unlock(&(mesh->mesh_mutex));
2014 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2015 if(!mesh || !node) {
2016 meshlink_errno = MESHLINK_EINVAL;
2020 pthread_mutex_lock(&(mesh->mesh_mutex));
2024 n->status.blacklisted = true;
2025 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2027 //Make blacklisting persistent in the config file
2028 append_config_file(mesh, n->name, "blacklisted", "yes");
2030 pthread_mutex_unlock(&(mesh->mesh_mutex));
2034 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2035 if(!mesh || !node) {
2036 meshlink_errno = MESHLINK_EINVAL;
2040 pthread_mutex_lock(&(mesh->mesh_mutex));
2042 node_t *n = (node_t *)node;
2043 n->status.blacklisted = false;
2045 //TODO: remove blacklisted = yes from the config file
2047 pthread_mutex_unlock(&(mesh->mesh_mutex));
2051 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2052 mesh->default_blacklist = blacklist;
2055 /* Hint that a hostname may be found at an address
2056 * See header file for detailed comment.
2058 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2059 if(!mesh || !node || !addr)
2062 // Ignore hints about ourself.
2063 if((node_t *)node == mesh->self)
2066 pthread_mutex_lock(&(mesh->mesh_mutex));
2068 char *host = NULL, *port = NULL, *str = NULL;
2069 sockaddr2str((const sockaddr_t *)addr, &host, &port);
2072 xasprintf(&str, "%s %s", host, port);
2073 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0))
2074 append_config_file(mesh, node->name, "Address", str);
2076 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2083 pthread_mutex_unlock(&(mesh->mesh_mutex));
2084 // @TODO do we want to fire off a connection attempt right away?
2087 /* Return an array of edges in the current network graph.
2088 * Data captures the current state and will not be updated.
2089 * Caller must deallocate data when done.
2091 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
2092 if(!mesh || !nmemb || (*nmemb && !edges)) {
2093 meshlink_errno = MESHLINK_EINVAL;
2097 pthread_mutex_lock(&(mesh->mesh_mutex));
2099 meshlink_edge_t **result = NULL;
2100 meshlink_edge_t *copy = NULL;
2101 int result_size = 0;
2103 result_size = mesh->edges->count;
2105 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
2106 if(result_size > *nmemb)
2107 result = realloc(edges, result_size * sizeof(meshlink_edge_t *));
2112 meshlink_edge_t **p = result;
2114 for splay_each(edge_t, e, mesh->edges) {
2115 // skip edges that do not represent a two-directional connection
2116 if((!e->reverse) || (e->reverse->to != e->from)) {
2121 // the first *nmemb members of result can be re-used
2123 copy = xzalloc(sizeof(*copy));
2126 copy->from = (meshlink_node_t *)e->from;
2127 copy->to = (meshlink_node_t *)e->to;
2128 copy->address = e->address.storage;
2129 copy->options = e->options;
2130 copy->weight = e->weight;
2133 // shrink result to the actual amount of memory used
2134 for(int i = *nmemb; i > result_size; i--)
2135 free(result[i - 1]);
2136 result = realloc(result, result_size * sizeof(meshlink_edge_t *));
2137 *nmemb = result_size;
2140 meshlink_errno = MESHLINK_ENOMEM;
2143 pthread_mutex_unlock(&(mesh->mesh_mutex));
2148 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2153 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2154 meshlink_channel_t *channel = connection->priv;
2157 node_t *n = channel->node;
2158 meshlink_handle_t *mesh = n->mesh;
2159 if(n->status.destroyed)
2160 meshlink_channel_close(mesh, channel);
2161 else if(channel->receive_cb)
2162 channel->receive_cb(mesh, channel, data, len);
2166 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2167 node_t *n = utcp_connection->utcp->priv;
2170 meshlink_handle_t *mesh = n->mesh;
2171 if(!mesh->channel_accept_cb)
2173 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2175 channel->c = utcp_connection;
2176 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2177 utcp_accept(utcp_connection, channel_recv, channel);
2182 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2183 node_t *n = utcp->priv;
2184 meshlink_handle_t *mesh = n->mesh;
2185 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2188 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2189 if(!mesh || !channel) {
2190 meshlink_errno = MESHLINK_EINVAL;
2194 channel->receive_cb = cb;
2197 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2198 node_t *n = (node_t *)source;
2201 utcp_recv(n->utcp, data, len);
2204 static void channel_poll(struct utcp_connection *connection, size_t len) {
2205 meshlink_channel_t *channel = connection->priv;
2208 node_t *n = channel->node;
2209 meshlink_handle_t *mesh = n->mesh;
2210 if(channel->poll_cb)
2211 channel->poll_cb(mesh, channel, len);
2214 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2215 channel->poll_cb = cb;
2216 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2219 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2221 meshlink_errno = MESHLINK_EINVAL;
2225 pthread_mutex_lock(&mesh->mesh_mutex);
2226 mesh->channel_accept_cb = cb;
2227 mesh->receive_cb = channel_receive;
2228 for splay_each(node_t, n, mesh->nodes) {
2229 if(!n->utcp && n != mesh->self)
2230 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2232 pthread_mutex_unlock(&mesh->mesh_mutex);
2235 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) {
2236 if(!mesh || !node) {
2237 meshlink_errno = MESHLINK_EINVAL;
2241 node_t *n = (node_t *)node;
2243 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2244 mesh->receive_cb = channel_receive;
2246 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2250 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2252 channel->receive_cb = cb;
2253 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2255 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2262 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) {
2263 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2266 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2267 if(!mesh || !channel) {
2268 meshlink_errno = MESHLINK_EINVAL;
2272 utcp_shutdown(channel->c, direction);
2275 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2276 if(!mesh || !channel) {
2277 meshlink_errno = MESHLINK_EINVAL;
2281 utcp_close(channel->c);
2285 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2286 if(!mesh || !channel) {
2287 meshlink_errno = MESHLINK_EINVAL;
2295 meshlink_errno = MESHLINK_EINVAL;
2299 // TODO: more finegrained locking.
2300 // Ideally we want to put the data into the UTCP connection's send buffer.
2301 // Then, preferrably only if there is room in the receiver window,
2302 // kick the meshlink thread to go send packets.
2304 pthread_mutex_lock(&mesh->mesh_mutex);
2305 ssize_t retval = utcp_send(channel->c, data, len);
2306 pthread_mutex_unlock(&mesh->mesh_mutex);
2309 meshlink_errno = MESHLINK_ENETWORK;
2313 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2314 if(!mesh || !channel) {
2315 meshlink_errno = MESHLINK_EINVAL;
2319 return channel->c->flags;
2322 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2323 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2324 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2325 if(mesh->node_status_cb)
2326 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2329 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2331 meshlink_errno = MESHLINK_EINVAL;
2335 pthread_mutex_lock(&mesh->mesh_mutex);
2337 if(mesh->discovery == enable)
2340 if(mesh->threadstarted) {
2342 discovery_start(mesh);
2344 discovery_stop(mesh);
2347 mesh->discovery = enable;
2350 pthread_mutex_unlock(&mesh->mesh_mutex);
2353 static void __attribute__((constructor)) meshlink_init(void) {
2356 randomize(&seed, sizeof(seed));
2360 static void __attribute__((destructor)) meshlink_exit(void) {
2364 /// Device class traits
2365 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2366 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2367 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2368 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2369 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN