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 static pthread_mutex_t global_mutex;
53 __thread meshlink_errno_t meshlink_errno;
54 meshlink_log_cb_t global_log_cb;
55 meshlink_log_level_t global_log_level;
57 //TODO: this can go away completely
58 const var_t variables[] = {
59 /* Server configuration */
60 {"AddressFamily", VAR_SERVER},
61 {"AutoConnect", VAR_SERVER | VAR_SAFE},
62 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
63 {"BindToInterface", VAR_SERVER},
64 {"Broadcast", VAR_SERVER | VAR_SAFE},
65 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
66 {"DecrementTTL", VAR_SERVER},
67 {"Device", VAR_SERVER},
68 {"DeviceType", VAR_SERVER},
69 {"DirectOnly", VAR_SERVER},
70 {"ECDSAPrivateKeyFile", VAR_SERVER},
71 {"ExperimentalProtocol", VAR_SERVER},
72 {"Forwarding", VAR_SERVER},
73 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
74 {"Hostnames", VAR_SERVER},
75 {"IffOneQueue", VAR_SERVER},
76 {"Interface", VAR_SERVER},
77 {"KeyExpire", VAR_SERVER},
78 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
79 {"LocalDiscovery", VAR_SERVER},
80 {"MACExpire", VAR_SERVER},
81 {"MaxConnectionBurst", VAR_SERVER},
82 {"MaxOutputBufferSize", VAR_SERVER},
83 {"MaxTimeout", VAR_SERVER},
84 {"Mode", VAR_SERVER | VAR_SAFE},
86 {"PingInterval", VAR_SERVER},
87 {"PingTimeout", VAR_SERVER},
88 {"PriorityInheritance", VAR_SERVER},
89 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
90 {"PrivateKeyFile", VAR_SERVER},
91 {"ProcessPriority", VAR_SERVER},
92 {"Proxy", VAR_SERVER},
93 {"ReplayWindow", VAR_SERVER},
94 {"ScriptsExtension", VAR_SERVER},
95 {"ScriptsInterpreter", VAR_SERVER},
96 {"StrictSubnets", VAR_SERVER},
97 {"TunnelServer", VAR_SERVER},
98 {"VDEGroup", VAR_SERVER},
99 {"VDEPort", VAR_SERVER},
100 /* Host configuration */
101 {"Address", VAR_HOST | VAR_MULTIPLE},
102 {"Cipher", VAR_SERVER | VAR_HOST},
103 {"ClampMSS", VAR_SERVER | VAR_HOST},
104 {"Compression", VAR_SERVER | VAR_HOST},
105 {"Digest", VAR_SERVER | VAR_HOST},
106 {"ECDSAPublicKey", VAR_HOST},
107 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
108 {"IndirectData", VAR_SERVER | VAR_HOST},
109 {"MACLength", VAR_SERVER | VAR_HOST},
110 {"PMTU", VAR_SERVER | VAR_HOST},
111 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
113 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
114 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
115 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
116 {"TCPOnly", VAR_SERVER | VAR_HOST},
117 {"Weight", VAR_HOST | VAR_SAFE},
121 static bool fcopy(FILE *out, const char *filename) {
122 FILE *in = fopen(filename, "r");
124 logger(NULL, MESHLINK_ERROR, "Could not open %s: %s\n", filename, strerror(errno));
130 while((len = fread(buf, 1, sizeof buf, in)))
131 fwrite(buf, len, 1, out);
136 static int rstrip(char *value) {
137 int len = strlen(value);
138 while(len && strchr("\t\r\n ", value[len - 1]))
143 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
145 if(!filename || (*hostname && *port))
148 FILE *f = fopen(filename, "r");
152 while(fgets(line, sizeof line, f)) {
156 p += strcspn(p, "\t =");
159 q = p + strspn(p, "\t ");
161 q += 1 + strspn(q + 1, "\t ");
163 p = q + strcspn(q, "\t ");
166 p += strspn(p, "\t ");
167 p[strcspn(p, "\t ")] = 0;
169 if(!*port && !strcasecmp(line, "Port")) {
171 } else if(!*hostname && !strcasecmp(line, "Address")) {
172 *hostname = xstrdup(q);
179 if(*hostname && *port)
185 static char *get_my_hostname(meshlink_handle_t* mesh) {
186 char *hostname = NULL;
188 char *hostport = NULL;
189 char *name = mesh->self->name;
190 char filename[PATH_MAX] = "";
194 // Use first Address statement in own host config file
195 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
196 scan_for_hostname(filename, &hostname, &port);
201 // If that doesn't work, guess externally visible hostname
202 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
203 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
204 struct addrinfo *aip = ai;
205 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
208 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
210 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
216 send(s, request, sizeof request - 1, 0);
217 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
220 if(line[len - 1] == '\n')
222 char *p = strrchr(line, '\n');
224 hostname = xstrdup(p + 1);
237 // Check that the hostname is reasonable
239 for(char *p = hostname; *p; p++) {
240 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
242 // If not, forget it.
252 f = fopen(filename, "a");
254 fprintf(f, "\nAddress = %s\n", hostname);
257 logger(mesh, MESHLINK_DEBUG, "Could not append Address to %s: %s\n", filename, strerror(errno));
262 if(strchr(hostname, ':'))
263 xasprintf(&hostport, "[%s]:%s", hostname, port);
265 xasprintf(&hostport, "%s:%s", hostname, port);
267 if(strchr(hostname, ':'))
268 xasprintf(&hostport, "[%s]", hostname);
270 hostport = xstrdup(hostname);
278 static char *get_line(const char **data) {
287 static char line[1024];
288 const char *end = strchr(*data, '\n');
289 size_t len = end ? end - *data : strlen(*data);
290 if(len >= sizeof line) {
291 logger(NULL, MESHLINK_ERROR, "Maximum line length exceeded!\n");
294 if(len && !isprint(**data))
297 memcpy(line, *data, len);
308 static char *get_value(const char *data, const char *var) {
309 char *line = get_line(&data);
313 char *sep = line + strcspn(line, " \t=");
314 char *val = sep + strspn(sep, " \t");
316 val += 1 + strspn(val + 1, " \t");
318 if(strcasecmp(line, var))
323 static bool try_bind(int port) {
324 struct addrinfo *ai = NULL;
325 struct addrinfo hint = {
326 .ai_flags = AI_PASSIVE,
327 .ai_family = AF_UNSPEC,
328 .ai_socktype = SOCK_STREAM,
329 .ai_protocol = IPPROTO_TCP,
333 snprintf(portstr, sizeof portstr, "%d", port);
335 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
339 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
344 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
357 static int check_port(meshlink_handle_t *mesh) {
358 for(int i = 0; i < 1000; i++) {
359 int port = 0x1000 + (rand() & 0x7fff);
361 char filename[PATH_MAX];
362 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
363 FILE *f = fopen(filename, "a");
365 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
369 fprintf(f, "Port = %d\n", port);
375 logger(mesh, MESHLINK_DEBUG, "Please change MeshLink's Port manually.\n");
379 static bool finalize_join(meshlink_handle_t *mesh) {
380 char *name = xstrdup(get_value(mesh->data, "Name"));
382 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
386 if(!check_id(name)) {
387 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
391 char filename[PATH_MAX];
392 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
394 FILE *f = fopen(filename, "w");
396 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
400 fprintf(f, "Name = %s\n", name);
402 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
403 FILE *fh = fopen(filename, "w");
405 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
410 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
411 // Other chunks go unfiltered to their respective host config files
412 const char *p = mesh->data;
415 while((l = get_line(&p))) {
420 // Split line into variable and value
421 int len = strcspn(l, "\t =");
423 value += strspn(value, "\t ");
426 value += strspn(value, "\t ");
431 if(!strcasecmp(l, "Name"))
432 if(strcmp(value, name))
436 else if(!strcasecmp(l, "NetName"))
439 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
442 for(i = 0; variables[i].name; i++) {
443 if(strcasecmp(l, variables[i].name))
449 // Ignore unknown and unsafe variables
451 logger(mesh, MESHLINK_DEBUG, "Ignoring unknown variable '%s' in invitation.\n", l);
453 } else if(!(variables[i].type & VAR_SAFE)) {
454 logger(mesh, MESHLINK_DEBUG, "Ignoring unsafe variable '%s' in invitation.\n", l);
458 // Copy the safe variable to the right config file
459 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
464 while(l && !strcasecmp(l, "Name")) {
465 if(!check_id(value)) {
466 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation.\n");
470 if(!strcmp(value, name)) {
471 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
475 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
476 f = fopen(filename, "w");
479 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
483 while((l = get_line(&p))) {
484 if(!strcmp(l, "#---------------------------------------------------------------#"))
486 int len = strcspn(l, "\t =");
487 if(len == 4 && !strncasecmp(l, "Name", 4)) {
489 value += strspn(value, "\t ");
492 value += strspn(value, "\t ");
505 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 return finalize_join(mesh);
560 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
561 shutdown(mesh->sock, SHUT_RDWR);
562 mesh->success = true;
572 static bool recvline(meshlink_handle_t* mesh, size_t len) {
573 char *newline = NULL;
578 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
579 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
580 if(result == -1 && errno == EINTR)
584 mesh->blen += result;
587 if(newline - mesh->buffer >= len)
590 len = newline - mesh->buffer;
592 memcpy(mesh->line, mesh->buffer, len);
594 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
595 mesh->blen -= len + 1;
599 static bool sendline(int fd, char *format, ...) {
600 static char buffer[4096];
605 va_start(ap, format);
606 blen = vsnprintf(buffer, sizeof buffer, format, ap);
609 if(blen < 1 || blen >= sizeof buffer)
616 int result = send(fd, p, blen, MSG_NOSIGNAL);
617 if(result == -1 && errno == EINTR)
628 static const char *errstr[] = {
629 [MESHLINK_OK] = "No error",
630 [MESHLINK_EINVAL] = "Invalid argument",
631 [MESHLINK_ENOMEM] = "Out of memory",
632 [MESHLINK_ENOENT] = "No such node",
633 [MESHLINK_EEXIST] = "Node already exists",
634 [MESHLINK_EINTERNAL] = "Internal error",
635 [MESHLINK_ERESOLV] = "Could not resolve hostname",
636 [MESHLINK_ESTORAGE] = "Storage error",
637 [MESHLINK_ENETWORK] = "Network error",
638 [MESHLINK_EPEER] = "Error communicating with peer",
641 const char *meshlink_strerror(meshlink_errno_t err) {
642 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
643 return "Invalid error code";
647 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
650 char pubname[PATH_MAX], privname[PATH_MAX];
652 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
654 if(!(key = ecdsa_generate())) {
655 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
656 meshlink_errno = MESHLINK_EINTERNAL;
659 logger(mesh, MESHLINK_DEBUG, "Done.\n");
661 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
662 f = fopen(privname, "w");
665 meshlink_errno = MESHLINK_ESTORAGE;
670 fchmod(fileno(f), 0600);
673 if(!ecdsa_write_pem_private_key(key, f)) {
674 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
677 meshlink_errno = MESHLINK_EINTERNAL;
683 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
684 f = fopen(pubname, "a");
687 meshlink_errno = MESHLINK_ESTORAGE;
691 char *pubkey = ecdsa_get_base64_public_key(key);
692 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
701 static bool meshlink_setup(meshlink_handle_t *mesh) {
702 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
703 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
704 meshlink_errno = MESHLINK_ESTORAGE;
708 char filename[PATH_MAX];
709 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
711 if(mkdir(filename, 0777) && errno != EEXIST) {
712 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
713 meshlink_errno = MESHLINK_ESTORAGE;
717 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
719 if(!access(filename, F_OK)) {
720 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
721 meshlink_errno = MESHLINK_EEXIST;
725 FILE *f = fopen(filename, "w");
727 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
728 meshlink_errno = MESHLINK_ESTORAGE;
732 fprintf(f, "Name = %s\n", mesh->name);
735 if(!ecdsa_keygen(mesh)) {
736 meshlink_errno = MESHLINK_EINTERNAL;
745 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname, dev_class_t devclass) {
746 return meshlink_open_with_size(confbase, name, appname, devclass, sizeof(meshlink_handle_t));
749 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, dev_class_t devclass, size_t size) {
751 // Validate arguments provided by the application
752 bool usingname = false;
754 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
756 if(!confbase || !*confbase) {
757 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
758 meshlink_errno = MESHLINK_EINVAL;
762 if(!appname || !*appname) {
763 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
764 meshlink_errno = MESHLINK_EINVAL;
768 if(!name || !*name) {
769 logger(NULL, MESHLINK_ERROR, "No name given!\n");
772 else { //check name only if there is a name != NULL
774 if(!check_id(name)) {
775 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
776 meshlink_errno = MESHLINK_EINVAL;
778 } else { usingname = true;}
781 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
782 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
783 meshlink_errno = MESHLINK_EINVAL;
787 meshlink_handle_t *mesh = xzalloc(size);
788 mesh->confbase = xstrdup(confbase);
789 mesh->appname = xstrdup(appname);
790 mesh->devclass = devclass;
791 if (usingname) mesh->name = xstrdup(name);
794 pthread_mutexattr_t attr;
795 pthread_mutexattr_init(&attr);
796 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
797 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
799 mesh->threadstarted = false;
800 event_loop_init(&mesh->loop);
801 mesh->loop.data = mesh;
803 // Check whether meshlink.conf already exists
805 char filename[PATH_MAX];
806 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
808 if(access(filename, R_OK)) {
809 if(errno == ENOENT) {
811 if(!meshlink_setup(mesh)) {
812 // meshlink_errno is set by meshlink_setup()
816 logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
817 meshlink_close(mesh);
818 meshlink_errno = MESHLINK_ESTORAGE;
823 // Read the configuration
825 init_configuration(&mesh->config);
827 if(!read_server_config(mesh)) {
828 meshlink_close(mesh);
829 meshlink_errno = MESHLINK_ESTORAGE;
834 struct WSAData wsa_state;
835 WSAStartup(MAKEWORD(2, 2), &wsa_state);
838 // Setup up everything
839 // TODO: we should not open listening sockets yet
841 if(!setup_network(mesh)) {
842 meshlink_close(mesh);
843 meshlink_errno = MESHLINK_ENETWORK;
847 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
851 static void *meshlink_main_loop(void *arg) {
852 meshlink_handle_t *mesh = arg;
854 pthread_mutex_lock(&(mesh->mesh_mutex));
856 try_outgoing_connections(mesh);
858 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
860 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
862 pthread_mutex_unlock(&(mesh->mesh_mutex));
866 bool meshlink_start(meshlink_handle_t *mesh) {
868 meshlink_errno = MESHLINK_EINVAL;
871 pthread_mutex_lock(&(mesh->mesh_mutex));
873 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
875 // TODO: open listening sockets first
877 //Check that a valid name is set
879 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
880 meshlink_errno = MESHLINK_EINVAL;
881 pthread_mutex_unlock(&(mesh->mesh_mutex));
885 // Start the main thread
887 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
888 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
889 memset(&mesh->thread, 0, sizeof mesh->thread);
890 meshlink_errno = MESHLINK_EINTERNAL;
891 pthread_mutex_unlock(&(mesh->mesh_mutex));
895 mesh->threadstarted=true;
897 discovery_start(mesh);
899 pthread_mutex_unlock(&(mesh->mesh_mutex));
903 void meshlink_stop(meshlink_handle_t *mesh) {
905 meshlink_errno = MESHLINK_EINVAL;
909 pthread_mutex_lock(&(mesh->mesh_mutex));
910 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
913 discovery_stop(mesh);
915 // Shut down a listening socket to signal the main thread to shut down
917 listen_socket_t *s = &mesh->listen_socket[0];
918 shutdown(s->tcp.fd, SHUT_RDWR);
920 // Wait for the main thread to finish
921 pthread_mutex_unlock(&(mesh->mesh_mutex));
922 pthread_join(mesh->thread, NULL);
923 pthread_mutex_lock(&(mesh->mesh_mutex));
925 mesh->threadstarted = false;
929 closesocket(s->tcp.fd);
930 io_del(&mesh->loop, &s->tcp);
931 s->tcp.fd = setup_listen_socket(&s->sa);
933 logger(mesh, MESHLINK_ERROR, "Could not repair listenen socket!");
935 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
937 pthread_mutex_unlock(&(mesh->mesh_mutex));
940 void meshlink_close(meshlink_handle_t *mesh) {
941 if(!mesh || !mesh->confbase) {
942 meshlink_errno = MESHLINK_EINVAL;
946 // lock is not released after this
947 pthread_mutex_lock(&(mesh->mesh_mutex));
949 // Close and free all resources used.
951 close_network_connections(mesh);
953 logger(mesh, MESHLINK_INFO, "Terminating");
955 exit_configuration(&mesh->config);
956 event_loop_exit(&mesh->loop);
963 ecdsa_free(mesh->invitation_key);
967 free(mesh->confbase);
968 pthread_mutex_destroy(&(mesh->mesh_mutex));
970 memset(mesh, 0, sizeof *mesh);
975 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
977 meshlink_errno = MESHLINK_EINVAL;
981 pthread_mutex_lock(&(mesh->mesh_mutex));
982 mesh->receive_cb = cb;
983 pthread_mutex_unlock(&(mesh->mesh_mutex));
986 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
988 meshlink_errno = MESHLINK_EINVAL;
992 pthread_mutex_lock(&(mesh->mesh_mutex));
993 mesh->node_status_cb = cb;
994 pthread_mutex_unlock(&(mesh->mesh_mutex));
997 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
999 pthread_mutex_lock(&(mesh->mesh_mutex));
1001 mesh->log_level = cb ? level : 0;
1002 pthread_mutex_unlock(&(mesh->mesh_mutex));
1005 global_log_level = cb ? level : 0;
1009 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1010 if(!mesh || !destination) {
1011 meshlink_errno = MESHLINK_EINVAL;
1019 meshlink_errno = MESHLINK_EINVAL;
1023 pthread_mutex_lock(&(mesh->mesh_mutex));
1025 //add packet to the queue
1026 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
1027 packet_in_queue->destination=destination;
1028 packet_in_queue->data=data;
1029 packet_in_queue->len=len;
1030 if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
1031 free(packet_in_queue);
1032 pthread_mutex_unlock(&(mesh->mesh_mutex));
1037 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1039 pthread_mutex_unlock(&(mesh->mesh_mutex));
1043 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
1044 pthread_mutex_lock(&(mesh->mesh_mutex));
1046 vpn_packet_t packet;
1047 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
1049 outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
1052 pthread_mutex_unlock(&(mesh->mesh_mutex));
1056 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
1057 pthread_mutex_unlock(&(mesh->mesh_mutex));
1062 packet.probe = false;
1063 memset(hdr, 0, sizeof *hdr);
1064 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1065 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1067 packet.len = sizeof *hdr + p->len;
1068 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1070 mesh->self->in_packets++;
1071 mesh->self->in_bytes += packet.len;
1072 route(mesh, mesh->self, &packet);
1074 pthread_mutex_unlock(&(mesh->mesh_mutex));
1078 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1079 if(!mesh || !destination) {
1080 meshlink_errno = MESHLINK_EINVAL;
1083 pthread_mutex_lock(&(mesh->mesh_mutex));
1085 node_t *n = (node_t *)destination;
1086 if(!n->status.reachable) {
1087 pthread_mutex_unlock(&(mesh->mesh_mutex));
1091 else if(n->mtuprobes > 30 && n->minmtu) {
1092 pthread_mutex_unlock(&(mesh->mesh_mutex));
1096 pthread_mutex_unlock(&(mesh->mesh_mutex));
1101 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1102 if(!mesh || !node) {
1103 meshlink_errno = MESHLINK_EINVAL;
1106 pthread_mutex_lock(&(mesh->mesh_mutex));
1108 node_t *n = (node_t *)node;
1110 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1111 meshlink_errno = MESHLINK_EINTERNAL;
1112 pthread_mutex_unlock(&(mesh->mesh_mutex));
1116 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1119 meshlink_errno = MESHLINK_EINTERNAL;
1121 pthread_mutex_unlock(&(mesh->mesh_mutex));
1125 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1126 if(!mesh || !name) {
1127 meshlink_errno = MESHLINK_EINVAL;
1131 meshlink_node_t *node = NULL;
1133 pthread_mutex_lock(&(mesh->mesh_mutex));
1134 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1135 pthread_mutex_unlock(&(mesh->mesh_mutex));
1139 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1140 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1141 meshlink_errno = MESHLINK_EINVAL;
1145 meshlink_node_t **result;
1148 pthread_mutex_lock(&(mesh->mesh_mutex));
1150 *nmemb = mesh->nodes->count;
1151 result = realloc(nodes, *nmemb * sizeof *nodes);
1154 meshlink_node_t **p = result;
1155 for splay_each(node_t, n, mesh->nodes)
1156 *p++ = (meshlink_node_t *)n;
1160 meshlink_errno = MESHLINK_ENOMEM;
1163 pthread_mutex_unlock(&(mesh->mesh_mutex));
1168 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1169 if(!mesh || !data || !len || !signature || !siglen) {
1170 meshlink_errno = MESHLINK_EINVAL;
1174 if(*siglen < MESHLINK_SIGLEN) {
1175 meshlink_errno = MESHLINK_EINVAL;
1179 pthread_mutex_lock(&(mesh->mesh_mutex));
1181 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1182 meshlink_errno = MESHLINK_EINTERNAL;
1183 pthread_mutex_unlock(&(mesh->mesh_mutex));
1187 *siglen = MESHLINK_SIGLEN;
1188 pthread_mutex_unlock(&(mesh->mesh_mutex));
1192 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1193 if(!mesh || !data || !len || !signature) {
1194 meshlink_errno = MESHLINK_EINVAL;
1198 if(siglen != MESHLINK_SIGLEN) {
1199 meshlink_errno = MESHLINK_EINVAL;
1203 pthread_mutex_lock(&(mesh->mesh_mutex));
1207 struct node_t *n = (struct node_t *)source;
1208 node_read_ecdsa_public_key(mesh, n);
1210 meshlink_errno = MESHLINK_EINTERNAL;
1213 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1215 pthread_mutex_unlock(&(mesh->mesh_mutex));
1219 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1220 char filename[PATH_MAX];
1222 pthread_mutex_lock(&(mesh->mesh_mutex));
1224 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1225 if(mkdir(filename, 0700) && errno != EEXIST) {
1226 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1227 meshlink_errno = MESHLINK_ESTORAGE;
1228 pthread_mutex_unlock(&(mesh->mesh_mutex));
1232 // Count the number of valid invitations, clean up old ones
1233 DIR *dir = opendir(filename);
1235 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1236 meshlink_errno = MESHLINK_ESTORAGE;
1237 pthread_mutex_unlock(&(mesh->mesh_mutex));
1244 time_t deadline = time(NULL) - 604800; // 1 week in the past
1246 while((ent = readdir(dir))) {
1247 if(strlen(ent->d_name) != 24)
1249 char invname[PATH_MAX];
1251 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1252 if(!stat(invname, &st)) {
1253 if(mesh->invitation_key && deadline < st.st_mtime)
1258 logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1264 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1266 meshlink_errno = MESHLINK_ESTORAGE;
1267 pthread_mutex_unlock(&(mesh->mesh_mutex));
1273 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1275 // Remove the key if there are no outstanding invitations.
1278 if(mesh->invitation_key) {
1279 ecdsa_free(mesh->invitation_key);
1280 mesh->invitation_key = NULL;
1284 if(mesh->invitation_key) {
1285 pthread_mutex_unlock(&(mesh->mesh_mutex));
1289 // Create a new key if necessary.
1290 FILE *f = fopen(filename, "r");
1292 if(errno != ENOENT) {
1293 logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1294 meshlink_errno = MESHLINK_ESTORAGE;
1295 pthread_mutex_unlock(&(mesh->mesh_mutex));
1299 mesh->invitation_key = ecdsa_generate();
1300 if(!mesh->invitation_key) {
1301 logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1302 meshlink_errno = MESHLINK_EINTERNAL;
1303 pthread_mutex_unlock(&(mesh->mesh_mutex));
1306 f = fopen(filename, "w");
1308 logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1309 meshlink_errno = MESHLINK_ESTORAGE;
1310 pthread_mutex_unlock(&(mesh->mesh_mutex));
1313 chmod(filename, 0600);
1314 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1317 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1319 if(!mesh->invitation_key) {
1320 logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1321 meshlink_errno = MESHLINK_ESTORAGE;
1325 pthread_mutex_unlock(&(mesh->mesh_mutex));
1326 return mesh->invitation_key;
1329 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1330 if(!mesh || !address) {
1331 meshlink_errno = MESHLINK_EINVAL;
1337 pthread_mutex_lock(&(mesh->mesh_mutex));
1339 for(const char *p = address; *p; p++) {
1340 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1342 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1343 meshlink_errno = MESHLINK_EINVAL;
1344 pthread_mutex_unlock(&(mesh->mesh_mutex));
1348 rval = append_config_file(mesh, mesh->self->name, "Address", address);
1349 pthread_mutex_unlock(&(mesh->mesh_mutex));
1353 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1355 meshlink_errno = MESHLINK_EINVAL;
1359 pthread_mutex_lock(&(mesh->mesh_mutex));
1361 // Check validity of the new node's name
1362 if(!check_id(name)) {
1363 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1364 meshlink_errno = MESHLINK_EINVAL;
1365 pthread_mutex_unlock(&(mesh->mesh_mutex));
1369 // Ensure no host configuration file with that name exists
1370 char filename[PATH_MAX];
1371 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1372 if(!access(filename, F_OK)) {
1373 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1374 meshlink_errno = MESHLINK_EEXIST;
1375 pthread_mutex_unlock(&(mesh->mesh_mutex));
1379 // Ensure no other nodes know about this name
1380 if(meshlink_get_node(mesh, name)) {
1381 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1382 meshlink_errno = MESHLINK_EEXIST;
1383 pthread_mutex_unlock(&(mesh->mesh_mutex));
1387 // Get the local address
1388 char *address = get_my_hostname(mesh);
1390 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1391 meshlink_errno = MESHLINK_ERESOLV;
1392 pthread_mutex_unlock(&(mesh->mesh_mutex));
1396 if(!refresh_invitation_key(mesh)) {
1397 meshlink_errno = MESHLINK_EINTERNAL;
1398 pthread_mutex_unlock(&(mesh->mesh_mutex));
1404 // Create a hash of the key.
1405 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1406 sha512(fingerprint, strlen(fingerprint), hash);
1407 b64encode_urlsafe(hash, hash, 18);
1409 // Create a random cookie for this invitation.
1411 randomize(cookie, 18);
1413 // Create a filename that doesn't reveal the cookie itself
1414 char buf[18 + strlen(fingerprint)];
1415 char cookiehash[64];
1416 memcpy(buf, cookie, 18);
1417 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1418 sha512(buf, sizeof buf, cookiehash);
1419 b64encode_urlsafe(cookiehash, cookiehash, 18);
1421 b64encode_urlsafe(cookie, cookie, 18);
1425 // Create a file containing the details of the invitation.
1426 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1427 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1429 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1430 meshlink_errno = MESHLINK_ESTORAGE;
1431 pthread_mutex_unlock(&(mesh->mesh_mutex));
1434 FILE *f = fdopen(ifd, "w");
1438 // Fill in the details.
1439 fprintf(f, "Name = %s\n", name);
1441 // fprintf(f, "NetName = %s\n", netname);
1442 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1444 // Copy Broadcast and Mode
1445 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1446 FILE *tc = fopen(filename, "r");
1449 while(fgets(buf, sizeof buf, tc)) {
1450 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1451 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1453 // Make sure there is a newline character.
1454 if(!strchr(buf, '\n'))
1460 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1461 meshlink_errno = MESHLINK_ESTORAGE;
1462 pthread_mutex_unlock(&(mesh->mesh_mutex));
1466 fprintf(f, "#---------------------------------------------------------------#\n");
1467 fprintf(f, "Name = %s\n", mesh->self->name);
1469 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1473 // Create an URL from the local address, key hash and cookie
1475 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1478 pthread_mutex_unlock(&(mesh->mesh_mutex));
1482 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1483 if(!mesh || !invitation) {
1484 meshlink_errno = MESHLINK_EINVAL;
1488 pthread_mutex_lock(&(mesh->mesh_mutex));
1490 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1491 char copy[strlen(invitation) + 1];
1492 strcpy(copy, invitation);
1494 // Split the invitation URL into hostname, port, key hash and cookie.
1496 char *slash = strchr(copy, '/');
1502 if(strlen(slash) != 48)
1505 char *address = copy;
1507 if(*address == '[') {
1509 char *bracket = strchr(address, ']');
1513 if(bracket[1] == ':')
1516 port = strchr(address, ':');
1524 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1527 // Generate a throw-away key for the invitation.
1528 ecdsa_t *key = ecdsa_generate();
1530 meshlink_errno = MESHLINK_EINTERNAL;
1531 pthread_mutex_unlock(&(mesh->mesh_mutex));
1535 char *b64key = ecdsa_get_base64_public_key(key);
1537 //Before doing meshlink_join make sure we are not connected to another mesh
1538 if ( mesh->threadstarted ){
1542 // Connect to the meshlink daemon mentioned in the URL.
1543 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1545 meshlink_errno = MESHLINK_ERESOLV;
1546 pthread_mutex_unlock(&(mesh->mesh_mutex));
1550 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1551 if(mesh->sock <= 0) {
1552 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1554 meshlink_errno = MESHLINK_ENETWORK;
1555 pthread_mutex_unlock(&(mesh->mesh_mutex));
1559 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1560 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1561 closesocket(mesh->sock);
1563 meshlink_errno = MESHLINK_ENETWORK;
1564 pthread_mutex_unlock(&(mesh->mesh_mutex));
1570 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1572 // Tell him we have an invitation, and give him our throw-away key.
1576 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1577 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1578 closesocket(mesh->sock);
1579 meshlink_errno = MESHLINK_ENETWORK;
1580 pthread_mutex_unlock(&(mesh->mesh_mutex));
1586 char hisname[4096] = "";
1587 int code, hismajor, hisminor = 0;
1589 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) {
1590 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1591 closesocket(mesh->sock);
1592 meshlink_errno = MESHLINK_ENETWORK;
1593 pthread_mutex_unlock(&(mesh->mesh_mutex));
1597 // Check if the hash of the key he gave us matches the hash in the URL.
1598 char *fingerprint = mesh->line + 2;
1600 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1601 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1602 meshlink_errno = MESHLINK_EINTERNAL;
1603 pthread_mutex_unlock(&(mesh->mesh_mutex));
1606 if(memcmp(hishash, mesh->hash, 18)) {
1607 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1608 meshlink_errno = MESHLINK_EPEER;
1609 pthread_mutex_unlock(&(mesh->mesh_mutex));
1614 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1616 meshlink_errno = MESHLINK_EINTERNAL;
1617 pthread_mutex_unlock(&(mesh->mesh_mutex));
1621 // Start an SPTPS session
1622 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1623 meshlink_errno = MESHLINK_EINTERNAL;
1624 pthread_mutex_unlock(&(mesh->mesh_mutex));
1628 // Feed rest of input buffer to SPTPS
1629 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1630 meshlink_errno = MESHLINK_EPEER;
1631 pthread_mutex_unlock(&(mesh->mesh_mutex));
1637 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1641 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1642 meshlink_errno = MESHLINK_ENETWORK;
1643 pthread_mutex_unlock(&(mesh->mesh_mutex));
1647 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1648 meshlink_errno = MESHLINK_EPEER;
1649 pthread_mutex_unlock(&(mesh->mesh_mutex));
1654 sptps_stop(&mesh->sptps);
1657 closesocket(mesh->sock);
1659 if(!mesh->success) {
1660 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
1661 meshlink_errno = MESHLINK_EPEER;
1662 pthread_mutex_unlock(&(mesh->mesh_mutex));
1666 pthread_mutex_unlock(&(mesh->mesh_mutex));
1670 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1671 meshlink_errno = MESHLINK_EINVAL;
1672 pthread_mutex_unlock(&(mesh->mesh_mutex));
1676 char *meshlink_export(meshlink_handle_t *mesh) {
1678 meshlink_errno = MESHLINK_EINVAL;
1682 pthread_mutex_lock(&(mesh->mesh_mutex));
1684 char filename[PATH_MAX];
1685 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1686 FILE *f = fopen(filename, "r");
1688 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
1689 meshlink_errno = MESHLINK_ESTORAGE;
1690 pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 fseek(f, 0, SEEK_END);
1695 int fsize = ftell(f);
1698 size_t len = fsize + 9 + strlen(mesh->self->name);
1699 char *buf = xmalloc(len);
1700 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1701 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1702 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
1704 meshlink_errno = MESHLINK_ESTORAGE;
1705 pthread_mutex_unlock(&(mesh->mesh_mutex));
1712 pthread_mutex_lock(&(mesh->mesh_mutex));
1716 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1717 if(!mesh || !data) {
1718 meshlink_errno = MESHLINK_EINVAL;
1722 pthread_mutex_lock(&(mesh->mesh_mutex));
1724 if(strncmp(data, "Name = ", 7)) {
1725 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1726 meshlink_errno = MESHLINK_EPEER;
1727 pthread_mutex_unlock(&(mesh->mesh_mutex));
1731 char *end = strchr(data + 7, '\n');
1733 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
1734 meshlink_errno = MESHLINK_EPEER;
1735 pthread_mutex_unlock(&(mesh->mesh_mutex));
1739 int len = end - (data + 7);
1741 memcpy(name, data + 7, len);
1743 if(!check_id(name)) {
1744 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
1745 meshlink_errno = MESHLINK_EPEER;
1746 pthread_mutex_unlock(&(mesh->mesh_mutex));
1750 char filename[PATH_MAX];
1751 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1752 if(!access(filename, F_OK)) {
1753 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
1754 meshlink_errno = MESHLINK_EEXIST;
1755 pthread_mutex_unlock(&(mesh->mesh_mutex));
1759 if(errno != ENOENT) {
1760 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
1761 meshlink_errno = MESHLINK_ESTORAGE;
1762 pthread_mutex_unlock(&(mesh->mesh_mutex));
1766 FILE *f = fopen(filename, "w");
1768 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
1769 meshlink_errno = MESHLINK_ESTORAGE;
1770 pthread_mutex_unlock(&(mesh->mesh_mutex));
1774 fwrite(end + 1, strlen(end + 1), 1, f);
1777 load_all_nodes(mesh);
1779 pthread_mutex_unlock(&(mesh->mesh_mutex));
1783 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1784 if(!mesh || !node) {
1785 meshlink_errno = MESHLINK_EINVAL;
1789 pthread_mutex_lock(&(mesh->mesh_mutex));
1793 n->status.blacklisted=true;
1794 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n",node->name);
1796 //Make blacklisting persistent in the config file
1797 append_config_file(mesh, n->name, "blacklisted", "yes");
1799 pthread_mutex_unlock(&(mesh->mesh_mutex));
1803 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1804 if(!mesh || !node) {
1805 meshlink_errno = MESHLINK_EINVAL;
1809 pthread_mutex_lock(&(mesh->mesh_mutex));
1811 node_t *n = (node_t *)node;
1812 n->status.blacklisted = false;
1814 //TODO: remove blacklisted = yes from the config file
1816 pthread_mutex_unlock(&(mesh->mesh_mutex));
1820 /* Hint that a hostname may be found at an address
1821 * See header file for detailed comment.
1823 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
1824 if(!mesh || !node || !addr)
1827 pthread_mutex_lock(&(mesh->mesh_mutex));
1829 char *host = NULL, *port = NULL, *str = NULL;
1830 sockaddr2str((const sockaddr_t *)addr, &host, &port);
1833 xasprintf(&str, "%s %s", host, port);
1834 append_config_file(mesh, node->name, "Address", str);
1841 pthread_mutex_unlock(&(mesh->mesh_mutex));
1842 // @TODO do we want to fire off a connection attempt right away?
1845 /* Return an array of edges in the current network graph.
1846 * Data captures the current state and will not be updated.
1847 * Caller must deallocate data when done.
1849 meshlink_edge_t **meshlink_get_all_edges_state(meshlink_handle_t *mesh, meshlink_edge_t **edges, size_t *nmemb) {
1850 if(!mesh || !nmemb || (*nmemb && !edges)) {
1851 meshlink_errno = MESHLINK_EINVAL;
1855 pthread_mutex_lock(&(mesh->mesh_mutex));
1857 meshlink_edge_t **result = NULL;
1858 meshlink_edge_t *copy = NULL;
1859 int result_size = 0;
1861 result_size = mesh->edges->count;
1863 // if result is smaller than edges, we have to dealloc all the excess meshlink_edge_t
1864 if(result_size > *nmemb) {
1865 result = realloc(edges, result_size * sizeof (meshlink_edge_t*));
1871 meshlink_edge_t **p = result;
1873 for splay_each(edge_t, e, mesh->edges) {
1874 // skip edges that do not represent a two-directional connection
1875 if((!e->reverse) || (e->reverse->to != e->from)) {
1880 // the first *nmemb members of result can be re-used
1882 copy = xzalloc(sizeof *copy);
1887 copy->from = (meshlink_node_t*)e->from;
1888 copy->to = (meshlink_node_t*)e->to;
1889 copy->address = e->address.storage;
1890 copy->options = e->options;
1891 copy->weight = e->weight;
1894 // shrink result to the actual amount of memory used
1895 for(int i = *nmemb; i > result_size; i--) {
1896 free(result[i - 1]);
1898 result = realloc(result, result_size * sizeof (meshlink_edge_t*));
1899 *nmemb = result_size;
1903 meshlink_errno = MESHLINK_ENOMEM;
1906 pthread_mutex_unlock(&(mesh->mesh_mutex));
1911 static void __attribute__((constructor)) meshlink_init(void) {
1915 static void __attribute__((destructor)) meshlink_exit(void) {
1920 /// Device class traits
1921 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX +1] = {
1922 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1923 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1924 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1925 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN