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"
44 #include "ed25519/sha512.h"
45 #include "discovery.h"
48 #define MSG_NOSIGNAL 0
51 __thread meshlink_errno_t meshlink_errno;
52 meshlink_log_cb_t global_log_cb;
53 meshlink_log_level_t global_log_level;
55 //TODO: this can go away completely
56 const var_t variables[] = {
57 /* Server configuration */
58 {"AddressFamily", VAR_SERVER},
59 {"AutoConnect", VAR_SERVER | VAR_SAFE},
60 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
61 {"BindToInterface", VAR_SERVER},
62 {"Broadcast", VAR_SERVER | VAR_SAFE},
63 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
64 {"DecrementTTL", VAR_SERVER},
65 {"Device", VAR_SERVER},
66 {"DeviceType", VAR_SERVER},
67 {"DirectOnly", VAR_SERVER},
68 {"ECDSAPrivateKeyFile", VAR_SERVER},
69 {"ExperimentalProtocol", VAR_SERVER},
70 {"Forwarding", VAR_SERVER},
71 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
72 {"Hostnames", VAR_SERVER},
73 {"IffOneQueue", VAR_SERVER},
74 {"Interface", VAR_SERVER},
75 {"KeyExpire", VAR_SERVER},
76 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
77 {"LocalDiscovery", VAR_SERVER},
78 {"MACExpire", VAR_SERVER},
79 {"MaxConnectionBurst", VAR_SERVER},
80 {"MaxOutputBufferSize", VAR_SERVER},
81 {"MaxTimeout", VAR_SERVER},
82 {"Mode", VAR_SERVER | VAR_SAFE},
84 {"PingInterval", VAR_SERVER},
85 {"PingTimeout", VAR_SERVER},
86 {"PriorityInheritance", VAR_SERVER},
87 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
88 {"PrivateKeyFile", VAR_SERVER},
89 {"ProcessPriority", VAR_SERVER},
90 {"Proxy", VAR_SERVER},
91 {"ReplayWindow", VAR_SERVER},
92 {"ScriptsExtension", VAR_SERVER},
93 {"ScriptsInterpreter", VAR_SERVER},
94 {"StrictSubnets", VAR_SERVER},
95 {"TunnelServer", VAR_SERVER},
96 {"VDEGroup", VAR_SERVER},
97 {"VDEPort", VAR_SERVER},
98 /* Host configuration */
99 {"Address", VAR_HOST | VAR_MULTIPLE},
100 {"Cipher", VAR_SERVER | VAR_HOST},
101 {"ClampMSS", VAR_SERVER | VAR_HOST},
102 {"Compression", VAR_SERVER | VAR_HOST},
103 {"Digest", VAR_SERVER | VAR_HOST},
104 {"ECDSAPublicKey", VAR_HOST},
105 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
106 {"IndirectData", VAR_SERVER | VAR_HOST},
107 {"MACLength", VAR_SERVER | VAR_HOST},
108 {"PMTU", VAR_SERVER | VAR_HOST},
109 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
111 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
112 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
113 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
114 {"TCPOnly", VAR_SERVER | VAR_HOST},
115 {"Weight", VAR_HOST | VAR_SAFE},
119 static bool fcopy(FILE *out, const char *filename) {
120 FILE *in = fopen(filename, "r");
122 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
128 while((len = fread(buf, 1, sizeof buf, in)))
129 fwrite(buf, len, 1, out);
134 static int rstrip(char *value) {
135 int len = strlen(value);
136 while(len && strchr("\t\r\n ", value[len - 1]))
141 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
143 if(!filename || (*hostname && *port))
146 FILE *f = fopen(filename, "r");
150 while(fgets(line, sizeof line, f)) {
154 p += strcspn(p, "\t =");
157 q = p + strspn(p, "\t ");
159 q += 1 + strspn(q + 1, "\t ");
161 p = q + strcspn(q, "\t ");
164 p += strspn(p, "\t ");
165 p[strcspn(p, "\t ")] = 0;
167 if(!*port && !strcasecmp(line, "Port")) {
169 } else if(!*hostname && !strcasecmp(line, "Address")) {
170 *hostname = xstrdup(q);
177 if(*hostname && *port)
183 static char *get_my_hostname(meshlink_handle_t* mesh) {
184 char *hostname = NULL;
186 char *hostport = NULL;
187 char *name = mesh->self->name;
188 char filename[PATH_MAX] = "";
192 // Use first Address statement in own host config file
193 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
194 scan_for_hostname(filename, &hostname, &port);
199 // If that doesn't work, guess externally visible hostname
200 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
201 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
202 struct addrinfo *aip = ai;
203 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
206 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
208 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
214 send(s, request, sizeof request - 1, 0);
215 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
218 if(line[len - 1] == '\n')
220 char *p = strrchr(line, '\n');
222 hostname = xstrdup(p + 1);
235 // Check that the hostname is reasonable
237 for(char *p = hostname; *p; p++) {
238 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
240 // If not, forget it.
250 f = fopen(filename, "a");
252 fprintf(f, "\nAddress = %s\n", hostname);
255 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
260 if(strchr(hostname, ':'))
261 xasprintf(&hostport, "[%s]:%s", hostname, port);
263 xasprintf(&hostport, "%s:%s", hostname, port);
265 if(strchr(hostname, ':'))
266 xasprintf(&hostport, "[%s]", hostname);
268 hostport = xstrdup(hostname);
276 static char *get_line(const char **data) {
285 static char line[1024];
286 const char *end = strchr(*data, '\n');
287 size_t len = end ? end - *data : strlen(*data);
288 if(len >= sizeof line) {
289 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
292 if(len && !isprint(**data))
295 memcpy(line, *data, len);
306 static char *get_value(const char *data, const char *var) {
307 char *line = get_line(&data);
311 char *sep = line + strcspn(line, " \t=");
312 char *val = sep + strspn(sep, " \t");
314 val += 1 + strspn(val + 1, " \t");
316 if(strcasecmp(line, var))
321 static bool try_bind(int port) {
322 struct addrinfo *ai = NULL;
323 struct addrinfo hint = {
324 .ai_flags = AI_PASSIVE,
325 .ai_family = AF_UNSPEC,
326 .ai_socktype = SOCK_STREAM,
327 .ai_protocol = IPPROTO_TCP,
331 snprintf(portstr, sizeof portstr, "%d", port);
333 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
337 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
342 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
355 static int check_port(meshlink_handle_t *mesh) {
356 for(int i = 0; i < 1000; i++) {
357 int port = 0x1000 + (rand() & 0x7fff);
359 char filename[PATH_MAX];
360 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
361 FILE *f = fopen(filename, "a");
363 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
367 fprintf(f, "Port = %d\n", port);
373 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
377 static bool finalize_join(meshlink_handle_t *mesh) {
378 char *name = xstrdup(get_value(mesh->data, "Name"));
380 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
384 if(!check_id(name)) {
385 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
389 char filename[PATH_MAX];
390 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
392 FILE *f = fopen(filename, "w");
394 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
398 fprintf(f, "Name = %s\n", name);
400 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
401 FILE *fh = fopen(filename, "w");
403 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
408 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
409 // Other chunks go unfiltered to their respective host config files
410 const char *p = mesh->data;
413 while((l = get_line(&p))) {
418 // Split line into variable and value
419 int len = strcspn(l, "\t =");
421 value += strspn(value, "\t ");
424 value += strspn(value, "\t ");
429 if(!strcasecmp(l, "Name"))
430 if(strcmp(value, name))
434 else if(!strcasecmp(l, "NetName"))
437 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
440 for(i = 0; variables[i].name; i++) {
441 if(strcasecmp(l, variables[i].name))
447 // Ignore unknown and unsafe variables
449 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
451 } else if(!(variables[i].type & VAR_SAFE)) {
452 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
456 // Copy the safe variable to the right config file
457 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
462 while(l && !strcasecmp(l, "Name")) {
463 if(!check_id(value)) {
464 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
468 if(!strcmp(value, name)) {
469 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
473 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
474 f = fopen(filename, "w");
477 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
481 while((l = get_line(&p))) {
482 if(!strcmp(l, "#---------------------------------------------------------------#"))
484 int len = strcspn(l, "\t =");
485 if(len == 4 && !strncasecmp(l, "Name", 4)) {
487 value += strspn(value, "\t ");
490 value += strspn(value, "\t ");
503 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
509 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
510 fprintf(fh, "Port = %s\n", mesh->myport);
514 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
517 free(mesh->self->name);
518 free(mesh->self->connection->name);
519 mesh->self->name = xstrdup(name);
520 mesh->self->connection->name = name;
522 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
524 load_all_nodes(mesh);
529 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
530 meshlink_handle_t* mesh = handle;
532 int result = send(mesh->sock, data, len, 0);
533 if(result == -1 && errno == EINTR)
543 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
544 meshlink_handle_t* mesh = handle;
546 case SPTPS_HANDSHAKE:
547 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
550 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
551 memcpy(mesh->data + mesh->thedatalen, msg, len);
552 mesh->thedatalen += len;
553 mesh->data[mesh->thedatalen] = 0;
557 mesh->thedatalen = 0;
558 return finalize_join(mesh);
561 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
562 shutdown(mesh->sock, SHUT_RDWR);
563 mesh->success = true;
573 static bool recvline(meshlink_handle_t* mesh, size_t len) {
574 char *newline = NULL;
579 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
580 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
581 if(result == -1 && errno == EINTR)
585 mesh->blen += result;
588 if(newline - mesh->buffer >= len)
591 len = newline - mesh->buffer;
593 memcpy(mesh->line, mesh->buffer, len);
595 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
596 mesh->blen -= len + 1;
600 static bool sendline(int fd, char *format, ...) {
601 static char buffer[4096];
606 va_start(ap, format);
607 blen = vsnprintf(buffer, sizeof buffer, format, ap);
610 if(blen < 1 || blen >= sizeof buffer)
617 int result = send(fd, p, blen, MSG_NOSIGNAL);
618 if(result == -1 && errno == EINTR)
629 static const char *errstr[] = {
630 [MESHLINK_OK] = "No error",
631 [MESHLINK_EINVAL] = "Invalid argument",
632 [MESHLINK_ENOMEM] = "Out of memory",
633 [MESHLINK_ENOENT] = "No such node",
634 [MESHLINK_EEXIST] = "Node already exists",
635 [MESHLINK_EINTERNAL] = "Internal error",
636 [MESHLINK_ERESOLV] = "Could not resolve hostname",
637 [MESHLINK_ESTORAGE] = "Storage error",
638 [MESHLINK_ENETWORK] = "Network error",
639 [MESHLINK_EPEER] = "Error communicating with peer",
642 const char *meshlink_strerror(meshlink_errno_t err) {
643 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
644 return "Invalid error code";
648 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
651 char pubname[PATH_MAX], privname[PATH_MAX];
653 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
655 if(!(key = ecdsa_generate())) {
656 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
657 meshlink_errno = MESHLINK_EINTERNAL;
660 logger(mesh, MESHLINK_DEBUG, "Done.\n");
662 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
663 f = fopen(privname, "wb");
666 meshlink_errno = MESHLINK_ESTORAGE;
671 fchmod(fileno(f), 0600);
674 if(!ecdsa_write_pem_private_key(key, f)) {
675 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
678 meshlink_errno = MESHLINK_EINTERNAL;
684 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
685 f = fopen(pubname, "a");
688 meshlink_errno = MESHLINK_ESTORAGE;
692 char *pubkey = ecdsa_get_base64_public_key(key);
693 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
702 static struct timeval idle(event_loop_t *loop, void *data) {
703 meshlink_handle_t *mesh = data;
704 struct timeval t, tmin = {3600, 0};
705 for splay_each(node_t, n, mesh->nodes) {
708 t = utcp_timeout(n->utcp);
709 if(timercmp(&t, &tmin, <))
715 // Find out what local address a socket would use if we connect to the given address.
716 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
717 // of both endpoints, but this will actually not send any UDP packet.
718 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
719 struct addrinfo *rai = NULL;
720 const struct addrinfo hint = {
721 .ai_family = AF_UNSPEC,
722 .ai_socktype = SOCK_DGRAM,
723 .ai_protocol = IPPROTO_UDP,
726 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai)
729 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
735 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
742 struct sockaddr_storage sn;
743 socklen_t sl = sizeof sn;
745 if(getsockname(sock, (struct sockaddr *)&sn, &sl))
748 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV))
754 // Get our local address(es) by simulating connecting to an Internet host.
755 static void add_local_addresses(meshlink_handle_t *mesh) {
756 char host[NI_MAXHOST];
757 char entry[MAX_STRING_SIZE];
761 if(getlocaladdrname("93.184.216.34", host, sizeof host)) {
762 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
763 append_config_file(mesh, mesh->name, "Address", entry);
768 if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof host)) {
769 snprintf(entry, sizeof entry, "%s %s", host, mesh->myport);
770 append_config_file(mesh, mesh->name, "Address", entry);
774 static bool meshlink_setup(meshlink_handle_t *mesh) {
775 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
776 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
777 meshlink_errno = MESHLINK_ESTORAGE;
781 char filename[PATH_MAX];
782 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
784 if(mkdir(filename, 0777) && errno != EEXIST) {
785 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
786 meshlink_errno = MESHLINK_ESTORAGE;
790 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
792 if(!access(filename, F_OK)) {
793 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
794 meshlink_errno = MESHLINK_EEXIST;
798 FILE *f = fopen(filename, "w");
800 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
801 meshlink_errno = MESHLINK_ESTORAGE;
805 fprintf(f, "Name = %s\n", mesh->name);
808 if(!ecdsa_keygen(mesh)) {
809 meshlink_errno = MESHLINK_EINTERNAL;
818 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
819 // Validate arguments provided by the application
820 bool usingname = false;
822 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
824 if(!confbase || !*confbase) {
825 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
826 meshlink_errno = MESHLINK_EINVAL;
830 if(!appname || !*appname) {
831 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
832 meshlink_errno = MESHLINK_EINVAL;
836 if(!name || !*name) {
837 logger(NULL, MESHLINK_ERROR, "No name given!\n");
840 else { //check name only if there is a name != NULL
842 if(!check_id(name)) {
843 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
844 meshlink_errno = MESHLINK_EINVAL;
846 } else { usingname = true;}
849 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
850 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
851 meshlink_errno = MESHLINK_EINVAL;
855 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
856 mesh->confbase = xstrdup(confbase);
857 mesh->appname = xstrdup(appname);
858 mesh->devclass = devclass;
859 if (usingname) mesh->name = xstrdup(name);
862 pthread_mutexattr_t attr;
863 pthread_mutexattr_init(&attr);
864 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
865 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
867 mesh->threadstarted = false;
868 event_loop_init(&mesh->loop);
869 mesh->loop.data = mesh;
871 // Check whether meshlink.conf already exists
873 char filename[PATH_MAX];
874 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
876 if(access(filename, R_OK)) {
877 if(errno == ENOENT) {
879 if(!meshlink_setup(mesh)) {
880 // meshlink_errno is set by meshlink_setup()
884 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
885 meshlink_close(mesh);
886 meshlink_errno = MESHLINK_ESTORAGE;
891 // Read the configuration
893 init_configuration(&mesh->config);
895 if(!read_server_config(mesh)) {
896 meshlink_close(mesh);
897 meshlink_errno = MESHLINK_ESTORAGE;
902 struct WSAData wsa_state;
903 WSAStartup(MAKEWORD(2, 2), &wsa_state);
906 // Setup up everything
907 // TODO: we should not open listening sockets yet
909 if(!setup_network(mesh)) {
910 meshlink_close(mesh);
911 meshlink_errno = MESHLINK_ENETWORK;
915 add_local_addresses(mesh);
917 idle_set(&mesh->loop, idle, mesh);
919 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
923 static void *meshlink_main_loop(void *arg) {
924 meshlink_handle_t *mesh = arg;
926 pthread_mutex_lock(&(mesh->mesh_mutex));
928 try_outgoing_connections(mesh);
930 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
932 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
934 pthread_mutex_unlock(&(mesh->mesh_mutex));
938 bool meshlink_start(meshlink_handle_t *mesh) {
940 meshlink_errno = MESHLINK_EINVAL;
943 pthread_mutex_lock(&(mesh->mesh_mutex));
945 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
947 mesh->thedatalen = 0;
949 // TODO: open listening sockets first
951 //Check that a valid name is set
953 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
954 meshlink_errno = MESHLINK_EINVAL;
955 pthread_mutex_unlock(&(mesh->mesh_mutex));
959 // Start the main thread
961 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
962 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
963 memset(&mesh->thread, 0, sizeof mesh->thread);
964 meshlink_errno = MESHLINK_EINTERNAL;
965 pthread_mutex_unlock(&(mesh->mesh_mutex));
969 mesh->threadstarted=true;
971 discovery_start(mesh);
973 pthread_mutex_unlock(&(mesh->mesh_mutex));
977 void meshlink_stop(meshlink_handle_t *mesh) {
979 meshlink_errno = MESHLINK_EINVAL;
983 pthread_mutex_lock(&(mesh->mesh_mutex));
984 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
987 discovery_stop(mesh);
989 // Shut down a listening socket to signal the main thread to shut down
991 listen_socket_t *s = &mesh->listen_socket[0];
992 shutdown(s->tcp.fd, SHUT_RDWR);
994 // Wait for the main thread to finish
995 pthread_mutex_unlock(&(mesh->mesh_mutex));
996 pthread_join(mesh->thread, NULL);
997 pthread_mutex_lock(&(mesh->mesh_mutex));
999 mesh->threadstarted = false;
1003 closesocket(s->tcp.fd);
1004 io_del(&mesh->loop, &s->tcp);
1005 s->tcp.fd = setup_listen_socket(&s->sa);
1007 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
1009 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
1011 pthread_mutex_unlock(&(mesh->mesh_mutex));
1014 void meshlink_close(meshlink_handle_t *mesh) {
1015 if(!mesh || !mesh->confbase) {
1016 meshlink_errno = MESHLINK_EINVAL;
1020 // stop can be called even if mesh has not been started
1021 meshlink_stop(mesh);
1023 // lock is not released after this
1024 pthread_mutex_lock(&(mesh->mesh_mutex));
1026 // Close and free all resources used.
1028 close_network_connections(mesh);
1030 logger(mesh, MESHLINK_INFO, "Terminating");
1032 exit_configuration(&mesh->config);
1033 event_loop_exit(&mesh->loop);
1040 ecdsa_free(mesh->invitation_key);
1043 free(mesh->appname);
1044 free(mesh->confbase);
1045 pthread_mutex_destroy(&(mesh->mesh_mutex));
1047 memset(mesh, 0, sizeof *mesh);
1052 static void deltree(const char *dirname) {
1053 DIR *d = opendir(dirname);
1056 while((ent = readdir(d))) {
1057 if(ent->d_name[0] == '.')
1059 char filename[PATH_MAX];
1060 snprintf(filename, sizeof filename, "%s" SLASH "%s", dirname, ent->d_name);
1061 if(unlink(filename))
1070 bool meshlink_destroy(const char *confbase) {
1072 meshlink_errno = MESHLINK_EINVAL;
1076 char filename[PATH_MAX];
1077 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
1079 if(unlink(filename)) {
1080 if(errno == ENOENT) {
1081 meshlink_errno = MESHLINK_ENOENT;
1084 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1085 meshlink_errno = MESHLINK_ESTORAGE;
1095 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1097 meshlink_errno = MESHLINK_EINVAL;
1101 pthread_mutex_lock(&(mesh->mesh_mutex));
1102 mesh->receive_cb = cb;
1103 pthread_mutex_unlock(&(mesh->mesh_mutex));
1106 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1108 meshlink_errno = MESHLINK_EINVAL;
1112 pthread_mutex_lock(&(mesh->mesh_mutex));
1113 mesh->node_status_cb = cb;
1114 pthread_mutex_unlock(&(mesh->mesh_mutex));
1117 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1119 pthread_mutex_lock(&(mesh->mesh_mutex));
1121 mesh->log_level = cb ? level : 0;
1122 pthread_mutex_unlock(&(mesh->mesh_mutex));
1125 global_log_level = cb ? level : 0;
1129 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1130 meshlink_packethdr_t *hdr;
1132 // Validate arguments
1133 if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1134 meshlink_errno = MESHLINK_EINVAL;
1142 meshlink_errno = MESHLINK_EINVAL;
1146 // Prepare the packet
1147 vpn_packet_t *packet = malloc(sizeof *packet);
1149 meshlink_errno = MESHLINK_ENOMEM;
1153 packet->probe = false;
1154 packet->tcp = false;
1155 packet->len = len + sizeof *hdr;
1157 hdr = (meshlink_packethdr_t *)packet->data;
1158 memset(hdr, 0, sizeof *hdr);
1159 // leave the last byte as 0 to make sure strings are always
1160 // null-terminated if they are longer than the buffer
1161 strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1162 strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1164 memcpy(packet->data + sizeof *hdr, data, len);
1167 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1169 meshlink_errno = MESHLINK_ENOMEM;
1173 // Notify event loop
1174 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1179 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1180 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1184 mesh->self->in_packets++;
1185 mesh->self->in_bytes += packet->len;
1186 route(mesh, mesh->self, packet);
1189 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1190 if(!mesh || !destination) {
1191 meshlink_errno = MESHLINK_EINVAL;
1194 pthread_mutex_lock(&(mesh->mesh_mutex));
1196 node_t *n = (node_t *)destination;
1197 if(!n->status.reachable) {
1198 pthread_mutex_unlock(&(mesh->mesh_mutex));
1202 else if(n->mtuprobes > 30 && n->minmtu) {
1203 pthread_mutex_unlock(&(mesh->mesh_mutex));
1207 pthread_mutex_unlock(&(mesh->mesh_mutex));
1212 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1213 if(!mesh || !node) {
1214 meshlink_errno = MESHLINK_EINVAL;
1217 pthread_mutex_lock(&(mesh->mesh_mutex));
1219 node_t *n = (node_t *)node;
1221 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1222 meshlink_errno = MESHLINK_EINTERNAL;
1223 pthread_mutex_unlock(&(mesh->mesh_mutex));
1227 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1230 meshlink_errno = MESHLINK_EINTERNAL;
1232 pthread_mutex_unlock(&(mesh->mesh_mutex));
1236 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1237 if(!mesh || !name) {
1238 meshlink_errno = MESHLINK_EINVAL;
1242 meshlink_node_t *node = NULL;
1244 pthread_mutex_lock(&(mesh->mesh_mutex));
1245 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1246 pthread_mutex_unlock(&(mesh->mesh_mutex));
1250 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1251 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1252 meshlink_errno = MESHLINK_EINVAL;
1256 meshlink_node_t **result;
1259 pthread_mutex_lock(&(mesh->mesh_mutex));
1261 *nmemb = mesh->nodes->count;
1262 result = realloc(nodes, *nmemb * sizeof *nodes);
1265 meshlink_node_t **p = result;
1266 for splay_each(node_t, n, mesh->nodes)
1267 *p++ = (meshlink_node_t *)n;
1271 meshlink_errno = MESHLINK_ENOMEM;
1274 pthread_mutex_unlock(&(mesh->mesh_mutex));
1279 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1280 if(!mesh || !data || !len || !signature || !siglen) {
1281 meshlink_errno = MESHLINK_EINVAL;
1285 if(*siglen < MESHLINK_SIGLEN) {
1286 meshlink_errno = MESHLINK_EINVAL;
1290 pthread_mutex_lock(&(mesh->mesh_mutex));
1292 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1293 meshlink_errno = MESHLINK_EINTERNAL;
1294 pthread_mutex_unlock(&(mesh->mesh_mutex));
1298 *siglen = MESHLINK_SIGLEN;
1299 pthread_mutex_unlock(&(mesh->mesh_mutex));
1303 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1304 if(!mesh || !data || !len || !signature) {
1305 meshlink_errno = MESHLINK_EINVAL;
1309 if(siglen != MESHLINK_SIGLEN) {
1310 meshlink_errno = MESHLINK_EINVAL;
1314 pthread_mutex_lock(&(mesh->mesh_mutex));
1318 struct node_t *n = (struct node_t *)source;
1319 node_read_ecdsa_public_key(mesh, n);
1321 meshlink_errno = MESHLINK_EINTERNAL;
1324 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1326 pthread_mutex_unlock(&(mesh->mesh_mutex));
1330 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1331 char filename[PATH_MAX];
1333 pthread_mutex_lock(&(mesh->mesh_mutex));
1335 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1336 if(mkdir(filename, 0700) && errno != EEXIST) {
1337 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1338 meshlink_errno = MESHLINK_ESTORAGE;
1339 pthread_mutex_unlock(&(mesh->mesh_mutex));
1343 // Count the number of valid invitations, clean up old ones
1344 DIR *dir = opendir(filename);
1346 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1347 meshlink_errno = MESHLINK_ESTORAGE;
1348 pthread_mutex_unlock(&(mesh->mesh_mutex));
1355 time_t deadline = time(NULL) - 604800; // 1 week in the past
1357 while((ent = readdir(dir))) {
1358 if(strlen(ent->d_name) != 24)
1360 char invname[PATH_MAX];
1362 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1363 if(!stat(invname, &st)) {
1364 if(mesh->invitation_key && deadline < st.st_mtime)
1369 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1375 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1377 meshlink_errno = MESHLINK_ESTORAGE;
1378 pthread_mutex_unlock(&(mesh->mesh_mutex));
1384 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1386 // Remove the key if there are no outstanding invitations.
1389 if(mesh->invitation_key) {
1390 ecdsa_free(mesh->invitation_key);
1391 mesh->invitation_key = NULL;
1395 if(mesh->invitation_key) {
1396 pthread_mutex_unlock(&(mesh->mesh_mutex));
1400 // Create a new key if necessary.
1401 FILE *f = fopen(filename, "rb");
1403 if(errno != ENOENT) {
1404 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1405 meshlink_errno = MESHLINK_ESTORAGE;
1406 pthread_mutex_unlock(&(mesh->mesh_mutex));
1410 mesh->invitation_key = ecdsa_generate();
1411 if(!mesh->invitation_key) {
1412 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1413 meshlink_errno = MESHLINK_EINTERNAL;
1414 pthread_mutex_unlock(&(mesh->mesh_mutex));
1417 f = fopen(filename, "wb");
1419 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1420 meshlink_errno = MESHLINK_ESTORAGE;
1421 pthread_mutex_unlock(&(mesh->mesh_mutex));
1424 chmod(filename, 0600);
1425 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1428 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1430 if(!mesh->invitation_key) {
1431 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1432 meshlink_errno = MESHLINK_ESTORAGE;
1436 pthread_mutex_unlock(&(mesh->mesh_mutex));
1437 return mesh->invitation_key;
1440 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1441 if(!mesh || !address) {
1442 meshlink_errno = MESHLINK_EINVAL;
1448 pthread_mutex_lock(&(mesh->mesh_mutex));
1450 for(const char *p = address; *p; p++) {
1451 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1453 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1454 meshlink_errno = MESHLINK_EINVAL;
1455 pthread_mutex_unlock(&(mesh->mesh_mutex));
1459 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1460 pthread_mutex_unlock(&(mesh->mesh_mutex));
1464 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1466 meshlink_errno = MESHLINK_EINVAL;
1470 pthread_mutex_lock(&(mesh->mesh_mutex));
1472 // Check validity of the new node's name
1473 if(!check_id(name)) {
1474 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1475 meshlink_errno = MESHLINK_EINVAL;
1476 pthread_mutex_unlock(&(mesh->mesh_mutex));
1480 // Ensure no host configuration file with that name exists
1481 char filename[PATH_MAX];
1482 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1483 if(!access(filename, F_OK)) {
1484 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1485 meshlink_errno = MESHLINK_EEXIST;
1486 pthread_mutex_unlock(&(mesh->mesh_mutex));
1490 // Ensure no other nodes know about this name
1491 if(meshlink_get_node(mesh, name)) {
1492 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1493 meshlink_errno = MESHLINK_EEXIST;
1494 pthread_mutex_unlock(&(mesh->mesh_mutex));
1498 // Get the local address
1499 char *address = get_my_hostname(mesh);
1501 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1502 meshlink_errno = MESHLINK_ERESOLV;
1503 pthread_mutex_unlock(&(mesh->mesh_mutex));
1507 if(!refresh_invitation_key(mesh)) {
1508 meshlink_errno = MESHLINK_EINTERNAL;
1509 pthread_mutex_unlock(&(mesh->mesh_mutex));
1515 // Create a hash of the key.
1516 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1517 sha512(fingerprint, strlen(fingerprint), hash);
1518 b64encode_urlsafe(hash, hash, 18);
1520 // Create a random cookie for this invitation.
1522 randomize(cookie, 18);
1524 // Create a filename that doesn't reveal the cookie itself
1525 char buf[18 + strlen(fingerprint)];
1526 char cookiehash[64];
1527 memcpy(buf, cookie, 18);
1528 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1529 sha512(buf, sizeof buf, cookiehash);
1530 b64encode_urlsafe(cookiehash, cookiehash, 18);
1532 b64encode_urlsafe(cookie, cookie, 18);
1536 // Create a file containing the details of the invitation.
1537 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1538 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1540 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1541 meshlink_errno = MESHLINK_ESTORAGE;
1542 pthread_mutex_unlock(&(mesh->mesh_mutex));
1545 FILE *f = fdopen(ifd, "w");
1549 // Fill in the details.
1550 fprintf(f, "Name = %s\n", name);
1552 // fprintf(f, "NetName = %s\n", netname);
1553 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1555 // Copy Broadcast and Mode
1556 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1557 FILE *tc = fopen(filename, "r");
1560 while(fgets(buf, sizeof buf, tc)) {
1561 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1562 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1564 // Make sure there is a newline character.
1565 if(!strchr(buf, '\n'))
1571 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1572 meshlink_errno = MESHLINK_ESTORAGE;
1573 pthread_mutex_unlock(&(mesh->mesh_mutex));
1577 fprintf(f, "#---------------------------------------------------------------#\n");
1578 fprintf(f, "Name = %s\n", mesh->self->name);
1580 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1584 // Create an URL from the local address, key hash and cookie
1586 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1589 pthread_mutex_unlock(&(mesh->mesh_mutex));
1593 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1594 if(!mesh || !invitation) {
1595 meshlink_errno = MESHLINK_EINVAL;
1599 pthread_mutex_lock(&(mesh->mesh_mutex));
1601 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1602 char copy[strlen(invitation) + 1];
1603 strcpy(copy, invitation);
1605 // Split the invitation URL into hostname, port, key hash and cookie.
1607 char *slash = strchr(copy, '/');
1613 if(strlen(slash) != 48)
1616 char *address = copy;
1618 if(*address == '[') {
1620 char *bracket = strchr(address, ']');
1624 if(bracket[1] == ':')
1627 port = strchr(address, ':');
1635 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1638 // Generate a throw-away key for the invitation.
1639 ecdsa_t *key = ecdsa_generate();
1641 meshlink_errno = MESHLINK_EINTERNAL;
1642 pthread_mutex_unlock(&(mesh->mesh_mutex));
1646 char *b64key = ecdsa_get_base64_public_key(key);
1648 //Before doing meshlink_join make sure we are not connected to another mesh
1649 if ( mesh->threadstarted ){
1653 // Connect to the meshlink daemon mentioned in the URL.
1654 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1656 meshlink_errno = MESHLINK_ERESOLV;
1657 pthread_mutex_unlock(&(mesh->mesh_mutex));
1661 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1662 if(mesh->sock <= 0) {
1663 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1665 meshlink_errno = MESHLINK_ENETWORK;
1666 pthread_mutex_unlock(&(mesh->mesh_mutex));
1670 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1671 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1672 closesocket(mesh->sock);
1674 meshlink_errno = MESHLINK_ENETWORK;
1675 pthread_mutex_unlock(&(mesh->mesh_mutex));
1681 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1683 // Tell him we have an invitation, and give him our throw-away key.
1687 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1688 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1689 closesocket(mesh->sock);
1690 meshlink_errno = MESHLINK_ENETWORK;
1691 pthread_mutex_unlock(&(mesh->mesh_mutex));
1697 char hisname[4096] = "";
1698 int code, hismajor, hisminor = 0;
1700 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) {
1701 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1702 closesocket(mesh->sock);
1703 meshlink_errno = MESHLINK_ENETWORK;
1704 pthread_mutex_unlock(&(mesh->mesh_mutex));
1708 // Check if the hash of the key he gave us matches the hash in the URL.
1709 char *fingerprint = mesh->line + 2;
1711 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1712 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1713 meshlink_errno = MESHLINK_EINTERNAL;
1714 pthread_mutex_unlock(&(mesh->mesh_mutex));
1717 if(memcmp(hishash, mesh->hash, 18)) {
1718 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1719 meshlink_errno = MESHLINK_EPEER;
1720 pthread_mutex_unlock(&(mesh->mesh_mutex));
1725 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1727 meshlink_errno = MESHLINK_EINTERNAL;
1728 pthread_mutex_unlock(&(mesh->mesh_mutex));
1732 // Start an SPTPS session
1733 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1734 meshlink_errno = MESHLINK_EINTERNAL;
1735 pthread_mutex_unlock(&(mesh->mesh_mutex));
1739 // Feed rest of input buffer to SPTPS
1740 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1741 meshlink_errno = MESHLINK_EPEER;
1742 pthread_mutex_unlock(&(mesh->mesh_mutex));
1748 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1752 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1753 meshlink_errno = MESHLINK_ENETWORK;
1754 pthread_mutex_unlock(&(mesh->mesh_mutex));
1758 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1759 meshlink_errno = MESHLINK_EPEER;
1760 pthread_mutex_unlock(&(mesh->mesh_mutex));
1765 sptps_stop(&mesh->sptps);
1768 closesocket(mesh->sock);
1770 if(!mesh->success) {
1771 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1772 meshlink_errno = MESHLINK_EPEER;
1773 pthread_mutex_unlock(&(mesh->mesh_mutex));
1777 pthread_mutex_unlock(&(mesh->mesh_mutex));
1781 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1782 meshlink_errno = MESHLINK_EINVAL;
1783 pthread_mutex_unlock(&(mesh->mesh_mutex));
1787 char *meshlink_export(meshlink_handle_t *mesh) {
1789 meshlink_errno = MESHLINK_EINVAL;
1793 pthread_mutex_lock(&(mesh->mesh_mutex));
1795 char filename[PATH_MAX];
1796 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1797 FILE *f = fopen(filename, "r");
1799 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1800 meshlink_errno = MESHLINK_ESTORAGE;
1801 pthread_mutex_unlock(&(mesh->mesh_mutex));
1805 fseek(f, 0, SEEK_END);
1806 int fsize = ftell(f);
1809 size_t len = fsize + 9 + strlen(mesh->self->name);
1810 char *buf = xmalloc(len);
1811 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1812 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1813 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1815 meshlink_errno = MESHLINK_ESTORAGE;
1816 pthread_mutex_unlock(&(mesh->mesh_mutex));
1823 pthread_mutex_unlock(&(mesh->mesh_mutex));
1827 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1828 if(!mesh || !data) {
1829 meshlink_errno = MESHLINK_EINVAL;
1833 pthread_mutex_lock(&(mesh->mesh_mutex));
1835 if(strncmp(data, "Name = ", 7)) {
1836 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1837 meshlink_errno = MESHLINK_EPEER;
1838 pthread_mutex_unlock(&(mesh->mesh_mutex));
1842 char *end = strchr(data + 7, '\n');
1844 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1845 meshlink_errno = MESHLINK_EPEER;
1846 pthread_mutex_unlock(&(mesh->mesh_mutex));
1850 int len = end - (data + 7);
1852 memcpy(name, data + 7, len);
1854 if(!check_id(name)) {
1855 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1856 meshlink_errno = MESHLINK_EPEER;
1857 pthread_mutex_unlock(&(mesh->mesh_mutex));
1861 char filename[PATH_MAX];
1862 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1863 if(!access(filename, F_OK)) {
1864 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1865 meshlink_errno = MESHLINK_EEXIST;
1866 pthread_mutex_unlock(&(mesh->mesh_mutex));
1870 if(errno != ENOENT) {
1871 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1872 meshlink_errno = MESHLINK_ESTORAGE;
1873 pthread_mutex_unlock(&(mesh->mesh_mutex));
1877 FILE *f = fopen(filename, "w");
1879 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1880 meshlink_errno = MESHLINK_ESTORAGE;
1881 pthread_mutex_unlock(&(mesh->mesh_mutex));
1885 fwrite(end + 1, strlen(end + 1), 1, f);
1888 load_all_nodes(mesh);
1890 pthread_mutex_unlock(&(mesh->mesh_mutex));
1894 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1895 if(!mesh || !node) {
1896 meshlink_errno = MESHLINK_EINVAL;
1900 pthread_mutex_lock(&(mesh->mesh_mutex));
1904 n->status.blacklisted=true;
1905 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1907 //Make blacklisting persistent in the config file
1908 append_config_file(mesh, n->name, "blacklisted", "yes");
1910 pthread_mutex_unlock(&(mesh->mesh_mutex));
1914 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1915 if(!mesh || !node) {
1916 meshlink_errno = MESHLINK_EINVAL;
1920 pthread_mutex_lock(&(mesh->mesh_mutex));
1922 node_t *n = (node_t *)node;
1923 n->status.blacklisted = false;
1925 //TODO: remove blacklisted = yes from the config file
1927 pthread_mutex_unlock(&(mesh->mesh_mutex));
1931 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
1932 mesh->default_blacklist = blacklist;
1935 /* Hint that a hostname may be found at an address
1936 * See header file for detailed comment.
1938 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1939 if(!mesh || !node || !addr)
1942 // Ignore hints about ourself.
1943 if((node_t *)node == mesh->self)
1946 pthread_mutex_lock(&(mesh->mesh_mutex));
1948 char *host = NULL, *port = NULL, *str = NULL;
1949 sockaddr2str((const sockaddr_t *)addr, &host, &port);
1952 xasprintf(&str, "%s %s", host, port);
1953 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
1954 append_config_file(mesh, node->name, "Address", str);
1956 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
1963 pthread_mutex_unlock(&(mesh->mesh_mutex));
1964 // @TODO do we want to fire off a connection attempt right away?
1967 /* Return an array of edges in the current network graph.
1968 * Data captures the current state and will not be updated.
1969 * Caller must deallocate data when done.
1971 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1972 if(!mesh || !nmemb || (*nmemb && !edges)) {
1973 meshlink_errno = MESHLINK_EINVAL;
1977 pthread_mutex_lock(&(mesh->mesh_mutex));
1979 meshlink_edge_t **result = NULL;
1980 meshlink_edge_t *copy = NULL;
1981 int result_size = 0;
1983 result_size = mesh->edges->count;
1985 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1986 if(result_size > *nmemb) {
1987 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1993 meshlink_edge_t **p = result;
1995 for splay_each(edge_t, e, mesh->edges) {
1996 // skip edges that do not represent a two-directional connection
1997 if((!e->reverse) || (e->reverse->to != e->from)) {
2002 // the first *nmemb members of result can be re-used
2004 copy = xzalloc(sizeof *copy);
2009 copy->from = (meshlink_node_t*)e->from;
2010 copy->to = (meshlink_node_t*)e->to;
2011 copy->address = e->address.storage;
2012 copy->options = e->options;
2013 copy->weight = e->weight;
2016 // shrink result to the actual amount of memory used
2017 for(int i = *nmemb; i > result_size; i--) {
2018 free(result[i - 1]);
2020 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
2021 *nmemb = result_size;
2025 meshlink_errno = MESHLINK_ENOMEM;
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2033 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2038 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2039 meshlink_channel_t *channel = connection->priv;
2042 node_t *n = channel->node;
2043 meshlink_handle_t *mesh = n->mesh;
2044 if(!channel->receive_cb)
2047 channel->receive_cb(mesh, channel, data, len);
2052 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2053 node_t *n = utcp_connection->utcp->priv;
2056 meshlink_handle_t *mesh = n->mesh;
2057 if(!mesh->channel_accept_cb)
2059 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2061 channel->c = utcp_connection;
2062 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
2063 utcp_accept(utcp_connection, channel_recv, channel);
2068 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2069 node_t *n = utcp->priv;
2070 meshlink_handle_t *mesh = n->mesh;
2071 char hex[len * 2 + 1];
2072 bin2hex(data, hex, len);
2073 logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
2074 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
2077 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2078 if(!mesh || !channel) {
2079 meshlink_errno = MESHLINK_EINVAL;
2083 channel->receive_cb = cb;
2086 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2087 node_t *n = (node_t *)source;
2090 char hex[len * 2 + 1];
2091 bin2hex(data, hex, len);
2092 logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
2093 utcp_recv(n->utcp, data, len);
2096 static void channel_poll(struct utcp_connection *connection, size_t len) {
2097 meshlink_channel_t *channel = connection->priv;
2100 node_t *n = channel->node;
2101 meshlink_handle_t *mesh = n->mesh;
2102 if(channel->poll_cb)
2103 channel->poll_cb(mesh, channel, len);
2106 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2107 channel->poll_cb = cb;
2108 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2111 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2113 meshlink_errno = MESHLINK_EINVAL;
2117 pthread_mutex_lock(&mesh->mesh_mutex);
2118 mesh->channel_accept_cb = cb;
2119 mesh->receive_cb = channel_receive;
2120 for splay_each(node_t, n, mesh->nodes) {
2121 if(!n->utcp && n != mesh->self) {
2122 logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
2123 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2126 pthread_mutex_unlock(&mesh->mesh_mutex);
2129 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) {
2130 if(!mesh || !node) {
2131 meshlink_errno = MESHLINK_EINVAL;
2135 logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
2136 node_t *n = (node_t *)node;
2138 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2139 mesh->receive_cb = channel_receive;
2141 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2145 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2147 channel->receive_cb = cb;
2148 channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2150 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2157 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2158 if(!mesh || !channel) {
2159 meshlink_errno = MESHLINK_EINVAL;
2163 utcp_shutdown(channel->c, direction);
2166 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2167 if(!mesh || !channel) {
2168 meshlink_errno = MESHLINK_EINVAL;
2172 utcp_close(channel->c);
2176 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2177 if(!mesh || !channel) {
2178 meshlink_errno = MESHLINK_EINVAL;
2186 meshlink_errno = MESHLINK_EINVAL;
2190 // TODO: more finegrained locking.
2191 // Ideally we want to put the data into the UTCP connection's send buffer.
2192 // Then, preferrably only if there is room in the receiver window,
2193 // kick the meshlink thread to go send packets.
2195 pthread_mutex_lock(&mesh->mesh_mutex);
2196 ssize_t retval = utcp_send(channel->c, data, len);
2197 pthread_mutex_unlock(&mesh->mesh_mutex);
2200 meshlink_errno = MESHLINK_ENETWORK;
2204 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2205 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2206 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2207 if(mesh->node_status_cb)
2208 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2211 static void __attribute__((constructor)) meshlink_init(void) {
2215 static void __attribute__((destructor)) meshlink_exit(void) {
2219 /// Device class traits
2220 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2221 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2222 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2223 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2224 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN