2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014 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;
705 for splay_each(node_t, n, mesh->nodes) {
708 t = utcp_timeout(n->utcp);
709 if(t >= 0 && t < tmin)
712 struct timeval tv = {.tv_sec = t};
716 static bool meshlink_setup(meshlink_handle_t *mesh) {
717 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
718 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
719 meshlink_errno = MESHLINK_ESTORAGE;
723 char filename[PATH_MAX];
724 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
726 if(mkdir(filename, 0777) && errno != EEXIST) {
727 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
728 meshlink_errno = MESHLINK_ESTORAGE;
732 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
734 if(!access(filename, F_OK)) {
735 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
736 meshlink_errno = MESHLINK_EEXIST;
740 FILE *f = fopen(filename, "w");
742 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
743 meshlink_errno = MESHLINK_ESTORAGE;
747 fprintf(f, "Name = %s\n", mesh->name);
750 if(!ecdsa_keygen(mesh)) {
751 meshlink_errno = MESHLINK_EINTERNAL;
760 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
761 // Validate arguments provided by the application
762 bool usingname = false;
764 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
766 if(!confbase || !*confbase) {
767 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
768 meshlink_errno = MESHLINK_EINVAL;
772 if(!appname || !*appname) {
773 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
774 meshlink_errno = MESHLINK_EINVAL;
778 if(!name || !*name) {
779 logger(NULL, MESHLINK_ERROR, "No name given!\n");
782 else { //check name only if there is a name != NULL
784 if(!check_id(name)) {
785 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
786 meshlink_errno = MESHLINK_EINVAL;
788 } else { usingname = true;}
791 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
792 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
793 meshlink_errno = MESHLINK_EINVAL;
797 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
798 mesh->confbase = xstrdup(confbase);
799 mesh->appname = xstrdup(appname);
800 mesh->devclass = devclass;
801 if (usingname) mesh->name = xstrdup(name);
804 pthread_mutexattr_t attr;
805 pthread_mutexattr_init(&attr);
806 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
807 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
809 mesh->threadstarted = false;
810 event_loop_init(&mesh->loop);
811 mesh->loop.data = mesh;
813 // Check whether meshlink.conf already exists
815 char filename[PATH_MAX];
816 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
818 if(access(filename, R_OK)) {
819 if(errno == ENOENT) {
821 if(!meshlink_setup(mesh)) {
822 // meshlink_errno is set by meshlink_setup()
826 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
827 meshlink_close(mesh);
828 meshlink_errno = MESHLINK_ESTORAGE;
833 // Read the configuration
835 init_configuration(&mesh->config);
837 if(!read_server_config(mesh)) {
838 meshlink_close(mesh);
839 meshlink_errno = MESHLINK_ESTORAGE;
844 struct WSAData wsa_state;
845 WSAStartup(MAKEWORD(2, 2), &wsa_state);
848 // Setup up everything
849 // TODO: we should not open listening sockets yet
851 if(!setup_network(mesh)) {
852 meshlink_close(mesh);
853 meshlink_errno = MESHLINK_ENETWORK;
857 idle_set(&mesh->loop, idle, mesh);
859 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
863 static void *meshlink_main_loop(void *arg) {
864 meshlink_handle_t *mesh = arg;
866 pthread_mutex_lock(&(mesh->mesh_mutex));
868 try_outgoing_connections(mesh);
870 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
872 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
874 pthread_mutex_unlock(&(mesh->mesh_mutex));
878 bool meshlink_start(meshlink_handle_t *mesh) {
880 meshlink_errno = MESHLINK_EINVAL;
883 pthread_mutex_lock(&(mesh->mesh_mutex));
885 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
887 mesh->thedatalen = 0;
889 // TODO: open listening sockets first
891 //Check that a valid name is set
893 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
894 meshlink_errno = MESHLINK_EINVAL;
895 pthread_mutex_unlock(&(mesh->mesh_mutex));
899 // Start the main thread
901 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
902 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
903 memset(&mesh->thread, 0, sizeof mesh->thread);
904 meshlink_errno = MESHLINK_EINTERNAL;
905 pthread_mutex_unlock(&(mesh->mesh_mutex));
909 mesh->threadstarted=true;
911 discovery_start(mesh);
913 pthread_mutex_unlock(&(mesh->mesh_mutex));
917 void meshlink_stop(meshlink_handle_t *mesh) {
919 meshlink_errno = MESHLINK_EINVAL;
923 pthread_mutex_lock(&(mesh->mesh_mutex));
924 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
927 discovery_stop(mesh);
929 // Shut down a listening socket to signal the main thread to shut down
931 listen_socket_t *s = &mesh->listen_socket[0];
932 shutdown(s->tcp.fd, SHUT_RDWR);
934 // Wait for the main thread to finish
935 pthread_mutex_unlock(&(mesh->mesh_mutex));
936 pthread_join(mesh->thread, NULL);
937 pthread_mutex_lock(&(mesh->mesh_mutex));
939 mesh->threadstarted = false;
943 closesocket(s->tcp.fd);
944 io_del(&mesh->loop, &s->tcp);
945 s->tcp.fd = setup_listen_socket(&s->sa);
947 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
949 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
951 pthread_mutex_unlock(&(mesh->mesh_mutex));
954 void meshlink_close(meshlink_handle_t *mesh) {
955 if(!mesh || !mesh->confbase) {
956 meshlink_errno = MESHLINK_EINVAL;
960 // lock is not released after this
961 pthread_mutex_lock(&(mesh->mesh_mutex));
963 // Close and free all resources used.
965 close_network_connections(mesh);
967 logger(mesh, MESHLINK_INFO, "Terminating");
969 exit_configuration(&mesh->config);
970 event_loop_exit(&mesh->loop);
977 ecdsa_free(mesh->invitation_key);
981 free(mesh->confbase);
982 pthread_mutex_destroy(&(mesh->mesh_mutex));
984 memset(mesh, 0, sizeof *mesh);
989 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
991 meshlink_errno = MESHLINK_EINVAL;
995 pthread_mutex_lock(&(mesh->mesh_mutex));
996 mesh->receive_cb = cb;
997 pthread_mutex_unlock(&(mesh->mesh_mutex));
1000 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1002 meshlink_errno = MESHLINK_EINVAL;
1006 pthread_mutex_lock(&(mesh->mesh_mutex));
1007 mesh->node_status_cb = cb;
1008 pthread_mutex_unlock(&(mesh->mesh_mutex));
1011 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1013 pthread_mutex_lock(&(mesh->mesh_mutex));
1015 mesh->log_level = cb ? level : 0;
1016 pthread_mutex_unlock(&(mesh->mesh_mutex));
1019 global_log_level = cb ? level : 0;
1023 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1024 meshlink_packethdr_t *hdr;
1026 // Validate arguments
1027 if(!mesh || !destination || len >= MAXSIZE - sizeof *hdr) {
1028 meshlink_errno = MESHLINK_EINVAL;
1036 meshlink_errno = MESHLINK_EINVAL;
1040 // Prepare the packet
1041 vpn_packet_t *packet = malloc(sizeof *packet);
1043 meshlink_errno = MESHLINK_ENOMEM;
1047 packet->probe = false;
1048 packet->tcp = false;
1049 packet->len = len + sizeof *hdr;
1051 hdr = (meshlink_packethdr_t *)packet->data;
1052 memset(hdr, 0, sizeof *hdr);
1053 // leave the last byte as 0 to make sure strings are always
1054 // null-terminated if they are longer than the buffer
1055 strncpy(hdr->destination, destination->name, (sizeof hdr->destination) - 1);
1056 strncpy(hdr->source, mesh->self->name, (sizeof hdr->source) -1 );
1058 memcpy(packet->data + sizeof *hdr, data, len);
1061 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1063 meshlink_errno = MESHLINK_ENOMEM;
1067 // Notify event loop
1068 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1073 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1074 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1078 mesh->self->in_packets++;
1079 mesh->self->in_bytes += packet->len;
1080 route(mesh, mesh->self, packet);
1083 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1084 if(!mesh || !destination) {
1085 meshlink_errno = MESHLINK_EINVAL;
1088 pthread_mutex_lock(&(mesh->mesh_mutex));
1090 node_t *n = (node_t *)destination;
1091 if(!n->status.reachable) {
1092 pthread_mutex_unlock(&(mesh->mesh_mutex));
1096 else if(n->mtuprobes > 30 && n->minmtu) {
1097 pthread_mutex_unlock(&(mesh->mesh_mutex));
1101 pthread_mutex_unlock(&(mesh->mesh_mutex));
1106 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1107 if(!mesh || !node) {
1108 meshlink_errno = MESHLINK_EINVAL;
1111 pthread_mutex_lock(&(mesh->mesh_mutex));
1113 node_t *n = (node_t *)node;
1115 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1116 meshlink_errno = MESHLINK_EINTERNAL;
1117 pthread_mutex_unlock(&(mesh->mesh_mutex));
1121 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1124 meshlink_errno = MESHLINK_EINTERNAL;
1126 pthread_mutex_unlock(&(mesh->mesh_mutex));
1130 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1131 if(!mesh || !name) {
1132 meshlink_errno = MESHLINK_EINVAL;
1136 meshlink_node_t *node = NULL;
1138 pthread_mutex_lock(&(mesh->mesh_mutex));
1139 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1140 pthread_mutex_unlock(&(mesh->mesh_mutex));
1144 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1145 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1146 meshlink_errno = MESHLINK_EINVAL;
1150 meshlink_node_t **result;
1153 pthread_mutex_lock(&(mesh->mesh_mutex));
1155 *nmemb = mesh->nodes->count;
1156 result = realloc(nodes, *nmemb * sizeof *nodes);
1159 meshlink_node_t **p = result;
1160 for splay_each(node_t, n, mesh->nodes)
1161 *p++ = (meshlink_node_t *)n;
1165 meshlink_errno = MESHLINK_ENOMEM;
1168 pthread_mutex_unlock(&(mesh->mesh_mutex));
1173 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1174 if(!mesh || !data || !len || !signature || !siglen) {
1175 meshlink_errno = MESHLINK_EINVAL;
1179 if(*siglen < MESHLINK_SIGLEN) {
1180 meshlink_errno = MESHLINK_EINVAL;
1184 pthread_mutex_lock(&(mesh->mesh_mutex));
1186 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1187 meshlink_errno = MESHLINK_EINTERNAL;
1188 pthread_mutex_unlock(&(mesh->mesh_mutex));
1192 *siglen = MESHLINK_SIGLEN;
1193 pthread_mutex_unlock(&(mesh->mesh_mutex));
1197 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1198 if(!mesh || !data || !len || !signature) {
1199 meshlink_errno = MESHLINK_EINVAL;
1203 if(siglen != MESHLINK_SIGLEN) {
1204 meshlink_errno = MESHLINK_EINVAL;
1208 pthread_mutex_lock(&(mesh->mesh_mutex));
1212 struct node_t *n = (struct node_t *)source;
1213 node_read_ecdsa_public_key(mesh, n);
1215 meshlink_errno = MESHLINK_EINTERNAL;
1218 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1220 pthread_mutex_unlock(&(mesh->mesh_mutex));
1224 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1225 char filename[PATH_MAX];
1227 pthread_mutex_lock(&(mesh->mesh_mutex));
1229 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1230 if(mkdir(filename, 0700) && errno != EEXIST) {
1231 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1232 meshlink_errno = MESHLINK_ESTORAGE;
1233 pthread_mutex_unlock(&(mesh->mesh_mutex));
1237 // Count the number of valid invitations, clean up old ones
1238 DIR *dir = opendir(filename);
1240 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1241 meshlink_errno = MESHLINK_ESTORAGE;
1242 pthread_mutex_unlock(&(mesh->mesh_mutex));
1249 time_t deadline = time(NULL) - 604800; // 1 week in the past
1251 while((ent = readdir(dir))) {
1252 if(strlen(ent->d_name) != 24)
1254 char invname[PATH_MAX];
1256 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1257 if(!stat(invname, &st)) {
1258 if(mesh->invitation_key && deadline < st.st_mtime)
1263 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1269 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1271 meshlink_errno = MESHLINK_ESTORAGE;
1272 pthread_mutex_unlock(&(mesh->mesh_mutex));
1278 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1280 // Remove the key if there are no outstanding invitations.
1283 if(mesh->invitation_key) {
1284 ecdsa_free(mesh->invitation_key);
1285 mesh->invitation_key = NULL;
1289 if(mesh->invitation_key) {
1290 pthread_mutex_unlock(&(mesh->mesh_mutex));
1294 // Create a new key if necessary.
1295 FILE *f = fopen(filename, "rb");
1297 if(errno != ENOENT) {
1298 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1299 meshlink_errno = MESHLINK_ESTORAGE;
1300 pthread_mutex_unlock(&(mesh->mesh_mutex));
1304 mesh->invitation_key = ecdsa_generate();
1305 if(!mesh->invitation_key) {
1306 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1307 meshlink_errno = MESHLINK_EINTERNAL;
1308 pthread_mutex_unlock(&(mesh->mesh_mutex));
1311 f = fopen(filename, "wb");
1313 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1314 meshlink_errno = MESHLINK_ESTORAGE;
1315 pthread_mutex_unlock(&(mesh->mesh_mutex));
1318 chmod(filename, 0600);
1319 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1322 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1324 if(!mesh->invitation_key) {
1325 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1326 meshlink_errno = MESHLINK_ESTORAGE;
1330 pthread_mutex_unlock(&(mesh->mesh_mutex));
1331 return mesh->invitation_key;
1334 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1335 if(!mesh || !address) {
1336 meshlink_errno = MESHLINK_EINVAL;
1342 pthread_mutex_lock(&(mesh->mesh_mutex));
1344 for(const char *p = address; *p; p++) {
1345 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1347 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1348 meshlink_errno = MESHLINK_EINVAL;
1349 pthread_mutex_unlock(&(mesh->mesh_mutex));
1353 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1354 pthread_mutex_unlock(&(mesh->mesh_mutex));
1358 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1360 meshlink_errno = MESHLINK_EINVAL;
1364 pthread_mutex_lock(&(mesh->mesh_mutex));
1366 // Check validity of the new node's name
1367 if(!check_id(name)) {
1368 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1369 meshlink_errno = MESHLINK_EINVAL;
1370 pthread_mutex_unlock(&(mesh->mesh_mutex));
1374 // Ensure no host configuration file with that name exists
1375 char filename[PATH_MAX];
1376 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1377 if(!access(filename, F_OK)) {
1378 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1379 meshlink_errno = MESHLINK_EEXIST;
1380 pthread_mutex_unlock(&(mesh->mesh_mutex));
1384 // Ensure no other nodes know about this name
1385 if(meshlink_get_node(mesh, name)) {
1386 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1387 meshlink_errno = MESHLINK_EEXIST;
1388 pthread_mutex_unlock(&(mesh->mesh_mutex));
1392 // Get the local address
1393 char *address = get_my_hostname(mesh);
1395 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1396 meshlink_errno = MESHLINK_ERESOLV;
1397 pthread_mutex_unlock(&(mesh->mesh_mutex));
1401 if(!refresh_invitation_key(mesh)) {
1402 meshlink_errno = MESHLINK_EINTERNAL;
1403 pthread_mutex_unlock(&(mesh->mesh_mutex));
1409 // Create a hash of the key.
1410 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1411 sha512(fingerprint, strlen(fingerprint), hash);
1412 b64encode_urlsafe(hash, hash, 18);
1414 // Create a random cookie for this invitation.
1416 randomize(cookie, 18);
1418 // Create a filename that doesn't reveal the cookie itself
1419 char buf[18 + strlen(fingerprint)];
1420 char cookiehash[64];
1421 memcpy(buf, cookie, 18);
1422 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1423 sha512(buf, sizeof buf, cookiehash);
1424 b64encode_urlsafe(cookiehash, cookiehash, 18);
1426 b64encode_urlsafe(cookie, cookie, 18);
1430 // Create a file containing the details of the invitation.
1431 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1432 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1434 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1435 meshlink_errno = MESHLINK_ESTORAGE;
1436 pthread_mutex_unlock(&(mesh->mesh_mutex));
1439 FILE *f = fdopen(ifd, "w");
1443 // Fill in the details.
1444 fprintf(f, "Name = %s\n", name);
1446 // fprintf(f, "NetName = %s\n", netname);
1447 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1449 // Copy Broadcast and Mode
1450 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1451 FILE *tc = fopen(filename, "r");
1454 while(fgets(buf, sizeof buf, tc)) {
1455 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1456 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1458 // Make sure there is a newline character.
1459 if(!strchr(buf, '\n'))
1465 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1466 meshlink_errno = MESHLINK_ESTORAGE;
1467 pthread_mutex_unlock(&(mesh->mesh_mutex));
1471 fprintf(f, "#---------------------------------------------------------------#\n");
1472 fprintf(f, "Name = %s\n", mesh->self->name);
1474 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1478 // Create an URL from the local address, key hash and cookie
1480 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1483 pthread_mutex_unlock(&(mesh->mesh_mutex));
1487 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1488 if(!mesh || !invitation) {
1489 meshlink_errno = MESHLINK_EINVAL;
1493 pthread_mutex_lock(&(mesh->mesh_mutex));
1495 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1496 char copy[strlen(invitation) + 1];
1497 strcpy(copy, invitation);
1499 // Split the invitation URL into hostname, port, key hash and cookie.
1501 char *slash = strchr(copy, '/');
1507 if(strlen(slash) != 48)
1510 char *address = copy;
1512 if(*address == '[') {
1514 char *bracket = strchr(address, ']');
1518 if(bracket[1] == ':')
1521 port = strchr(address, ':');
1529 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1532 // Generate a throw-away key for the invitation.
1533 ecdsa_t *key = ecdsa_generate();
1535 meshlink_errno = MESHLINK_EINTERNAL;
1536 pthread_mutex_unlock(&(mesh->mesh_mutex));
1540 char *b64key = ecdsa_get_base64_public_key(key);
1542 //Before doing meshlink_join make sure we are not connected to another mesh
1543 if ( mesh->threadstarted ){
1547 // Connect to the meshlink daemon mentioned in the URL.
1548 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1550 meshlink_errno = MESHLINK_ERESOLV;
1551 pthread_mutex_unlock(&(mesh->mesh_mutex));
1555 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1556 if(mesh->sock <= 0) {
1557 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1559 meshlink_errno = MESHLINK_ENETWORK;
1560 pthread_mutex_unlock(&(mesh->mesh_mutex));
1564 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1565 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1566 closesocket(mesh->sock);
1568 meshlink_errno = MESHLINK_ENETWORK;
1569 pthread_mutex_unlock(&(mesh->mesh_mutex));
1575 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1577 // Tell him we have an invitation, and give him our throw-away key.
1581 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1582 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1583 closesocket(mesh->sock);
1584 meshlink_errno = MESHLINK_ENETWORK;
1585 pthread_mutex_unlock(&(mesh->mesh_mutex));
1591 char hisname[4096] = "";
1592 int code, hismajor, hisminor = 0;
1594 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) {
1595 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1596 closesocket(mesh->sock);
1597 meshlink_errno = MESHLINK_ENETWORK;
1598 pthread_mutex_unlock(&(mesh->mesh_mutex));
1602 // Check if the hash of the key he gave us matches the hash in the URL.
1603 char *fingerprint = mesh->line + 2;
1605 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1606 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1607 meshlink_errno = MESHLINK_EINTERNAL;
1608 pthread_mutex_unlock(&(mesh->mesh_mutex));
1611 if(memcmp(hishash, mesh->hash, 18)) {
1612 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1613 meshlink_errno = MESHLINK_EPEER;
1614 pthread_mutex_unlock(&(mesh->mesh_mutex));
1619 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1621 meshlink_errno = MESHLINK_EINTERNAL;
1622 pthread_mutex_unlock(&(mesh->mesh_mutex));
1626 // Start an SPTPS session
1627 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1628 meshlink_errno = MESHLINK_EINTERNAL;
1629 pthread_mutex_unlock(&(mesh->mesh_mutex));
1633 // Feed rest of input buffer to SPTPS
1634 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1635 meshlink_errno = MESHLINK_EPEER;
1636 pthread_mutex_unlock(&(mesh->mesh_mutex));
1642 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1646 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1647 meshlink_errno = MESHLINK_ENETWORK;
1648 pthread_mutex_unlock(&(mesh->mesh_mutex));
1652 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1653 meshlink_errno = MESHLINK_EPEER;
1654 pthread_mutex_unlock(&(mesh->mesh_mutex));
1659 sptps_stop(&mesh->sptps);
1662 closesocket(mesh->sock);
1664 if(!mesh->success) {
1665 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1666 meshlink_errno = MESHLINK_EPEER;
1667 pthread_mutex_unlock(&(mesh->mesh_mutex));
1671 pthread_mutex_unlock(&(mesh->mesh_mutex));
1675 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1676 meshlink_errno = MESHLINK_EINVAL;
1677 pthread_mutex_unlock(&(mesh->mesh_mutex));
1681 char *meshlink_export(meshlink_handle_t *mesh) {
1683 meshlink_errno = MESHLINK_EINVAL;
1687 pthread_mutex_lock(&(mesh->mesh_mutex));
1689 char filename[PATH_MAX];
1690 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1691 FILE *f = fopen(filename, "r");
1693 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1694 meshlink_errno = MESHLINK_ESTORAGE;
1695 pthread_mutex_unlock(&(mesh->mesh_mutex));
1699 fseek(f, 0, SEEK_END);
1700 int fsize = ftell(f);
1703 size_t len = fsize + 9 + strlen(mesh->self->name);
1704 char *buf = xmalloc(len);
1705 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1706 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1707 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1709 meshlink_errno = MESHLINK_ESTORAGE;
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1717 pthread_mutex_unlock(&(mesh->mesh_mutex));
1721 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1722 if(!mesh || !data) {
1723 meshlink_errno = MESHLINK_EINVAL;
1727 pthread_mutex_lock(&(mesh->mesh_mutex));
1729 if(strncmp(data, "Name = ", 7)) {
1730 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1731 meshlink_errno = MESHLINK_EPEER;
1732 pthread_mutex_unlock(&(mesh->mesh_mutex));
1736 char *end = strchr(data + 7, '\n');
1738 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1739 meshlink_errno = MESHLINK_EPEER;
1740 pthread_mutex_unlock(&(mesh->mesh_mutex));
1744 int len = end - (data + 7);
1746 memcpy(name, data + 7, len);
1748 if(!check_id(name)) {
1749 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1750 meshlink_errno = MESHLINK_EPEER;
1751 pthread_mutex_unlock(&(mesh->mesh_mutex));
1755 char filename[PATH_MAX];
1756 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1757 if(!access(filename, F_OK)) {
1758 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1759 meshlink_errno = MESHLINK_EEXIST;
1760 pthread_mutex_unlock(&(mesh->mesh_mutex));
1764 if(errno != ENOENT) {
1765 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1766 meshlink_errno = MESHLINK_ESTORAGE;
1767 pthread_mutex_unlock(&(mesh->mesh_mutex));
1771 FILE *f = fopen(filename, "w");
1773 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1774 meshlink_errno = MESHLINK_ESTORAGE;
1775 pthread_mutex_unlock(&(mesh->mesh_mutex));
1779 fwrite(end + 1, strlen(end + 1), 1, f);
1782 load_all_nodes(mesh);
1784 pthread_mutex_unlock(&(mesh->mesh_mutex));
1788 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1789 if(!mesh || !node) {
1790 meshlink_errno = MESHLINK_EINVAL;
1794 pthread_mutex_lock(&(mesh->mesh_mutex));
1798 n->status.blacklisted=true;
1799 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1801 //Make blacklisting persistent in the config file
1802 append_config_file(mesh, n->name, "blacklisted", "yes");
1804 pthread_mutex_unlock(&(mesh->mesh_mutex));
1808 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1809 if(!mesh || !node) {
1810 meshlink_errno = MESHLINK_EINVAL;
1814 pthread_mutex_lock(&(mesh->mesh_mutex));
1816 node_t *n = (node_t *)node;
1817 n->status.blacklisted = false;
1819 //TODO: remove blacklisted = yes from the config file
1821 pthread_mutex_unlock(&(mesh->mesh_mutex));
1825 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
1826 mesh->default_blacklist = blacklist;
1829 /* Hint that a hostname may be found at an address
1830 * See header file for detailed comment.
1832 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1833 if(!mesh || !node || !addr)
1836 pthread_mutex_lock(&(mesh->mesh_mutex));
1838 char *host = NULL, *port = NULL, *str = NULL;
1839 sockaddr2str((const sockaddr_t *)addr, &host, &port);
1842 xasprintf(&str, "%s %s", host, port);
1843 if ( (strncmp ("fe80",host,4) != 0) && ( strncmp("127.",host,4) != 0 ) && ( strcmp("localhost",host) !=0 ) )
1844 append_config_file(mesh, node->name, "Address", str);
1846 logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
1853 pthread_mutex_unlock(&(mesh->mesh_mutex));
1854 // @TODO do we want to fire off a connection attempt right away?
1857 /* Return an array of edges in the current network graph.
1858 * Data captures the current state and will not be updated.
1859 * Caller must deallocate data when done.
1861 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1862 if(!mesh || !nmemb || (*nmemb && !edges)) {
1863 meshlink_errno = MESHLINK_EINVAL;
1867 pthread_mutex_lock(&(mesh->mesh_mutex));
1869 meshlink_edge_t **result = NULL;
1870 meshlink_edge_t *copy = NULL;
1871 int result_size = 0;
1873 result_size = mesh->edges->count;
1875 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1876 if(result_size > *nmemb) {
1877 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1883 meshlink_edge_t **p = result;
1885 for splay_each(edge_t, e, mesh->edges) {
1886 // skip edges that do not represent a two-directional connection
1887 if((!e->reverse) || (e->reverse->to != e->from)) {
1892 // the first *nmemb members of result can be re-used
1894 copy = xzalloc(sizeof *copy);
1899 copy->from = (meshlink_node_t*)e->from;
1900 copy->to = (meshlink_node_t*)e->to;
1901 copy->address = e->address.storage;
1902 copy->options = e->options;
1903 copy->weight = e->weight;
1906 // shrink result to the actual amount of memory used
1907 for(int i = *nmemb; i > result_size; i--) {
1908 free(result[i - 1]);
1910 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
1911 *nmemb = result_size;
1915 meshlink_errno = MESHLINK_ENOMEM;
1918 pthread_mutex_unlock(&(mesh->mesh_mutex));
1923 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
1928 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
1929 meshlink_channel_t *channel = connection->priv;
1932 node_t *n = channel->node;
1933 meshlink_handle_t *mesh = n->mesh;
1934 if(!channel->receive_cb)
1937 channel->receive_cb(mesh, channel, data, len);
1942 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
1943 node_t *n = utcp_connection->utcp->priv;
1946 meshlink_handle_t *mesh = n->mesh;
1947 if(!mesh->channel_accept_cb)
1949 meshlink_channel_t *channel = xzalloc(sizeof *channel);
1951 channel->c = utcp_connection;
1952 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0))
1953 utcp_accept(utcp_connection, channel_recv, channel);
1958 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
1959 node_t *n = utcp->priv;
1960 meshlink_handle_t *mesh = n->mesh;
1961 char hex[len * 2 + 1];
1962 bin2hex(data, hex, len);
1963 logger(mesh, MESHLINK_WARNING, "channel_send(%p, %p, %zu): %s\n", utcp, data, len, hex);
1964 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? len : -1;
1967 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
1968 if(!mesh || !channel) {
1969 meshlink_errno = MESHLINK_EINVAL;
1973 channel->receive_cb = cb;
1976 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
1977 node_t *n = (node_t *)source;
1980 char hex[len * 2 + 1];
1981 bin2hex(data, hex, len);
1982 logger(mesh, MESHLINK_WARNING, "channel_receive(%p, %p, %zu): %s\n", n->utcp, data, len, hex);
1983 utcp_recv(n->utcp, data, len);
1986 static void channel_poll(struct utcp_connection *connection, size_t len) {
1987 meshlink_channel_t *channel = connection->priv;
1990 node_t *n = channel->node;
1991 meshlink_handle_t *mesh = n->mesh;
1992 if(channel->poll_cb)
1993 channel->poll_cb(mesh, channel, len);
1996 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
1997 channel->poll_cb = cb;
1998 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2001 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2003 meshlink_errno = MESHLINK_EINVAL;
2007 pthread_mutex_lock(&mesh->mesh_mutex);
2008 mesh->channel_accept_cb = cb;
2009 mesh->receive_cb = channel_receive;
2010 for splay_each(node_t, n, mesh->nodes) {
2011 if(!n->utcp && n != mesh->self) {
2012 logger(mesh, MESHLINK_WARNING, "utcp_init on node %s", n->name);
2013 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2016 pthread_mutex_unlock(&mesh->mesh_mutex);
2019 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) {
2020 if(!mesh || !node) {
2021 meshlink_errno = MESHLINK_EINVAL;
2025 logger(mesh, MESHLINK_WARNING, "meshlink_channel_open(%p, %s, %u, %p, %p, %zu)\n", mesh, node->name, port, cb, data, len);
2026 node_t *n = (node_t *)node;
2028 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2029 mesh->receive_cb = channel_receive;
2031 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2035 meshlink_channel_t *channel = xzalloc(sizeof *channel);
2037 channel->receive_cb = cb;
2038 channel->c = utcp_connect(n->utcp, port, channel_recv, channel);
2040 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2047 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2048 if(!mesh || !channel) {
2049 meshlink_errno = MESHLINK_EINVAL;
2053 utcp_shutdown(channel->c, direction);
2056 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2057 if(!mesh || !channel) {
2058 meshlink_errno = MESHLINK_EINVAL;
2062 utcp_close(channel->c);
2066 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2067 if(!mesh || !channel) {
2068 meshlink_errno = MESHLINK_EINVAL;
2076 meshlink_errno = MESHLINK_EINVAL;
2080 // TODO: more finegrained locking.
2081 // Ideally we want to put the data into the UTCP connection's send buffer.
2082 // Then, preferrably only if there is room in the receiver window,
2083 // kick the meshlink thread to go send packets.
2085 pthread_mutex_lock(&mesh->mesh_mutex);
2086 ssize_t retval = utcp_send(channel->c, data, len);
2087 pthread_mutex_unlock(&mesh->mesh_mutex);
2090 meshlink_errno = MESHLINK_ENETWORK;
2094 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2095 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp)
2096 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2097 if(mesh->node_status_cb)
2098 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2101 static void __attribute__((constructor)) meshlink_init(void) {
2105 static void __attribute__((destructor)) meshlink_exit(void) {
2109 /// Device class traits
2110 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
2111 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2112 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2113 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2114 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN