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 */
36 #include "meshlink_internal.h"
43 #include "ed25519/sha512.h"
44 #include "discovery.h"
47 #define MSG_NOSIGNAL 0
50 static pthread_mutex_t global_mutex;
51 static bool discovery_started;
53 __thread meshlink_errno_t meshlink_errno;
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 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "Please change MeshLink's Port manually.\n");
367 fprintf(f, "Port = %d\n", port);
373 fprintf(stderr, "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 fprintf(stderr, "No Name found in invitation!\n");
384 if(!check_id(name)) {
385 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "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 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
451 } else if(!(variables[i].type & VAR_SAFE)) {
452 fprintf(stderr, "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 fprintf(stderr, "Invalid Name found in invitation.\n");
468 if(!strcmp(value, name)) {
469 fprintf(stderr, "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 fprintf(stderr, "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);
507 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
508 fprintf(fh, "Port = %s\n", mesh->myport);
512 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
515 free(mesh->self->name);
516 free(mesh->self->connection->name);
517 mesh->self->name = xstrdup(name);
518 mesh->self->connection->name = name;
520 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
522 load_all_nodes(mesh);
527 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
528 meshlink_handle_t* mesh = handle;
530 int result = send(mesh->sock, data, len, 0);
531 if(result == -1 && errno == EINTR)
541 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
542 meshlink_handle_t* mesh = handle;
544 case SPTPS_HANDSHAKE:
545 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
548 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
549 memcpy(mesh->data + mesh->thedatalen, msg, len);
550 mesh->thedatalen += len;
551 mesh->data[mesh->thedatalen] = 0;
555 return finalize_join(mesh);
558 fprintf(stderr, "Invitation succesfully accepted.\n");
559 shutdown(mesh->sock, SHUT_RDWR);
560 mesh->success = true;
570 static bool recvline(meshlink_handle_t* mesh, size_t len) {
571 char *newline = NULL;
576 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
577 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
578 if(result == -1 && errno == EINTR)
582 mesh->blen += result;
585 if(newline - mesh->buffer >= len)
588 len = newline - mesh->buffer;
590 memcpy(mesh->line, mesh->buffer, len);
592 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
593 mesh->blen -= len + 1;
597 static bool sendline(int fd, char *format, ...) {
598 static char buffer[4096];
603 va_start(ap, format);
604 blen = vsnprintf(buffer, sizeof buffer, format, ap);
607 if(blen < 1 || blen >= sizeof buffer)
614 int result = send(fd, p, blen, MSG_NOSIGNAL);
615 if(result == -1 && errno == EINTR)
626 static const char *errstr[] = {
627 [MESHLINK_OK] = "No error",
628 [MESHLINK_EINVAL] = "Invalid argument",
629 [MESHLINK_ENOMEM] = "Out of memory",
630 [MESHLINK_ENOENT] = "No such node",
631 [MESHLINK_EEXIST] = "Node already exists",
632 [MESHLINK_EINTERNAL] = "Internal error",
633 [MESHLINK_ERESOLV] = "Could not resolve hostname",
634 [MESHLINK_ESTORAGE] = "Storage error",
635 [MESHLINK_ENETWORK] = "Network error",
636 [MESHLINK_EPEER] = "Error communicating with peer",
639 const char *meshlink_strerror(meshlink_errno_t err) {
640 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
641 return "Invalid error code";
645 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
648 char pubname[PATH_MAX], privname[PATH_MAX];
650 fprintf(stderr, "Generating ECDSA keypair:\n");
652 if(!(key = ecdsa_generate())) {
653 fprintf(stderr, "Error during key generation!\n");
654 meshlink_errno = MESHLINK_EINTERNAL;
657 fprintf(stderr, "Done.\n");
659 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
660 f = fopen(privname, "w");
663 meshlink_errno = MESHLINK_ESTORAGE;
668 fchmod(fileno(f), 0600);
671 if(!ecdsa_write_pem_private_key(key, f)) {
672 fprintf(stderr, "Error writing private key!\n");
675 meshlink_errno = MESHLINK_EINTERNAL;
681 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
682 f = fopen(pubname, "a");
685 meshlink_errno = MESHLINK_ESTORAGE;
689 char *pubkey = ecdsa_get_base64_public_key(key);
690 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
699 static bool meshlink_setup(meshlink_handle_t *mesh) {
700 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
701 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
702 meshlink_errno = MESHLINK_ESTORAGE;
706 char filename[PATH_MAX];
707 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
709 if(mkdir(filename, 0777) && errno != EEXIST) {
710 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
711 meshlink_errno = MESHLINK_ESTORAGE;
715 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
717 if(!access(filename, F_OK)) {
718 fprintf(stderr, "Configuration file %s already exists!\n", filename);
719 meshlink_errno = MESHLINK_EEXIST;
723 FILE *f = fopen(filename, "w");
725 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
726 meshlink_errno = MESHLINK_ESTORAGE;
730 fprintf(f, "Name = %s\n", mesh->name);
733 if(!ecdsa_keygen(mesh)) {
734 meshlink_errno = MESHLINK_EINTERNAL;
743 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname) {
744 return meshlink_open_with_size(confbase, name, appname, sizeof(meshlink_handle_t));
747 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, size_t size) {
749 // Validate arguments provided by the application
750 bool usingname = false;
752 if(!confbase || !*confbase) {
753 fprintf(stderr, "No confbase given!\n");
754 meshlink_errno = MESHLINK_EINVAL;
758 if(!appname || !*appname) {
759 fprintf(stderr, "No appname given!\n");
760 meshlink_errno = MESHLINK_EINVAL;
764 if(!name || !*name) {
765 fprintf(stderr, "No name given!\n");
768 else { //check name only if there is a name != NULL
770 if(!check_id(name)) {
771 fprintf(stderr, "Invalid name given!\n");
772 meshlink_errno = MESHLINK_EINVAL;
774 } else { usingname = true;}
777 meshlink_handle_t *mesh = xzalloc(size);
778 mesh->confbase = xstrdup(confbase);
779 mesh->appname = xstrdup(appname);
780 if (usingname) mesh->name = xstrdup(name);
781 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
782 mesh->threadstarted = false;
783 event_loop_init(&mesh->loop);
784 mesh->loop.data = mesh;
786 // TODO: should be set by a function.
787 mesh->debug_level = 5;
789 // Check whether meshlink.conf already exists
791 char filename[PATH_MAX];
792 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
794 if(access(filename, R_OK)) {
795 if(errno == ENOENT) {
797 if(!meshlink_setup(mesh)) {
798 // meshlink_errno is set by meshlink_setup()
802 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
803 meshlink_close(mesh);
804 meshlink_errno = MESHLINK_ESTORAGE;
809 // Read the configuration
811 init_configuration(&mesh->config);
813 if(!read_server_config(mesh)) {
814 meshlink_close(mesh);
815 meshlink_errno = MESHLINK_ESTORAGE;
820 struct WSAData wsa_state;
821 WSAStartup(MAKEWORD(2, 2), &wsa_state);
824 // Setup up everything
825 // TODO: we should not open listening sockets yet
827 if(!setup_network(mesh)) {
828 meshlink_close(mesh);
829 meshlink_errno = MESHLINK_ENETWORK;
836 static void *meshlink_main_loop(void *arg) {
837 meshlink_handle_t *mesh = arg;
839 try_outgoing_connections(mesh);
841 fprintf(stderr, "Starting main_loop...\n");
843 fprintf(stderr, "main_loop returned.\n");
848 bool meshlink_start(meshlink_handle_t *mesh) {
850 fprintf(stderr, "meshlink_start called\n");
853 meshlink_errno = MESHLINK_EINVAL;
857 // TODO: open listening sockets first
859 //Check that a valid name is set
861 fprintf(stderr, "No name given!\n");
862 meshlink_errno = MESHLINK_EINVAL;
866 // Start the main thread
868 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
869 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
870 memset(&mesh->thread, 0, sizeof mesh->thread);
871 meshlink_errno = MESHLINK_EINTERNAL;
875 mesh->threadstarted=true;
878 // Since only one Avahi instance can run in one program at the moment, make sure we only start one, ignore it otherwise.
880 bool discovery_on = false;
881 pthread_mutex_lock(&global_mutex);
882 if(!discovery_started)
883 discovery_on = discovery_started = true;
884 pthread_mutex_unlock(&global_mutex);
887 discovery_start(mesh);
892 void meshlink_stop(meshlink_handle_t *mesh) {
894 fprintf(stderr, "meshlink_stop called\n");
897 meshlink_errno = MESHLINK_EINVAL;
903 bool discovery_on = mesh->discovery_threadstarted;
904 discovery_stop(mesh);
906 pthread_mutex_lock(&global_mutex);
907 discovery_started = false;
908 pthread_mutex_unlock(&global_mutex);
911 // Shut down a listening socket to signal the main thread to shut down
913 listen_socket_t *s = &mesh->listen_socket[0];
914 shutdown(s->tcp.fd, SHUT_RDWR);
916 // Wait for the main thread to finish
918 pthread_join(mesh->thread, NULL);
919 mesh->threadstarted = false;
923 closesocket(s->tcp.fd);
924 io_del(&mesh->loop, &s->tcp);
925 s->tcp.fd = setup_listen_socket(&s->sa);
927 logger(DEBUG_ALWAYS, LOG_ERR, "Could not repair listenen socket!");
929 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
932 void meshlink_close(meshlink_handle_t *mesh) {
933 if(!mesh || !mesh->confbase) {
934 meshlink_errno = MESHLINK_EINVAL;
938 // Close and free all resources used.
940 close_network_connections(mesh);
942 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
944 exit_configuration(&mesh->config);
945 event_loop_exit(&mesh->loop);
952 ecdsa_free(mesh->invitation_key);
955 free(mesh->confbase);
957 memset(mesh, 0, sizeof *mesh);
962 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
964 meshlink_errno = MESHLINK_EINVAL;
968 mesh->receive_cb = cb;
971 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
973 meshlink_errno = MESHLINK_EINVAL;
977 mesh->node_status_cb = cb;
980 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
982 meshlink_errno = MESHLINK_EINVAL;
987 mesh->log_level = level;
990 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
991 if(!mesh || !destination) {
992 meshlink_errno = MESHLINK_EINVAL;
1000 meshlink_errno = MESHLINK_EINVAL;
1004 //add packet to the queue
1005 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
1006 packet_in_queue->destination=destination;
1007 packet_in_queue->data=data;
1008 packet_in_queue->len=len;
1009 if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
1010 free(packet_in_queue);
1015 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1019 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
1020 vpn_packet_t packet;
1021 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
1023 outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
1027 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
1032 packet.probe = false;
1033 memset(hdr, 0, sizeof *hdr);
1034 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1035 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1037 packet.len = sizeof *hdr + p->len;
1038 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1040 mesh->self->in_packets++;
1041 mesh->self->in_bytes += packet.len;
1042 route(mesh, mesh->self, &packet);
1046 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1047 if(!mesh || !destination) {
1048 meshlink_errno = MESHLINK_EINVAL;
1052 node_t *n = (node_t *)destination;
1053 if(!n->status.reachable)
1055 else if(n->mtuprobes > 30 && n->minmtu)
1061 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1062 if(!mesh || !node) {
1063 meshlink_errno = MESHLINK_EINVAL;
1067 node_t *n = (node_t *)node;
1069 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1070 meshlink_errno = MESHLINK_EINTERNAL;
1074 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1077 meshlink_errno = MESHLINK_EINTERNAL;
1082 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1083 if(!mesh || !name) {
1084 meshlink_errno = MESHLINK_EINVAL;
1088 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1091 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1092 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1093 meshlink_errno = MESHLINK_EINVAL;
1097 meshlink_node_t **result;
1100 pthread_mutex_lock(&(mesh->nodes_mutex));
1102 *nmemb = mesh->nodes->count;
1103 result = realloc(nodes, *nmemb * sizeof *nodes);
1106 meshlink_node_t **p = result;
1107 for splay_each(node_t, n, mesh->nodes)
1108 *p++ = (meshlink_node_t *)n;
1112 meshlink_errno = MESHLINK_ENOMEM;
1115 pthread_mutex_unlock(&(mesh->nodes_mutex));
1120 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1121 if(!mesh || !data || !len || !signature || !siglen) {
1122 meshlink_errno = MESHLINK_EINVAL;
1126 if(*siglen < MESHLINK_SIGLEN) {
1127 meshlink_errno = MESHLINK_EINVAL;
1131 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1132 meshlink_errno = MESHLINK_EINTERNAL;
1136 *siglen = MESHLINK_SIGLEN;
1140 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1141 if(!mesh || !data || !len || !signature) {
1142 meshlink_errno = MESHLINK_EINVAL;
1146 if(siglen != MESHLINK_SIGLEN) {
1147 meshlink_errno = MESHLINK_EINVAL;
1151 struct node_t *n = (struct node_t *)source;
1152 node_read_ecdsa_public_key(mesh, n);
1154 meshlink_errno = MESHLINK_EINTERNAL;
1158 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1161 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1162 char filename[PATH_MAX];
1164 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1165 if(mkdir(filename, 0700) && errno != EEXIST) {
1166 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1167 meshlink_errno = MESHLINK_ESTORAGE;
1171 // Count the number of valid invitations, clean up old ones
1172 DIR *dir = opendir(filename);
1174 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1175 meshlink_errno = MESHLINK_ESTORAGE;
1182 time_t deadline = time(NULL) - 604800; // 1 week in the past
1184 while((ent = readdir(dir))) {
1185 if(strlen(ent->d_name) != 24)
1187 char invname[PATH_MAX];
1189 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1190 if(!stat(invname, &st)) {
1191 if(mesh->invitation_key && deadline < st.st_mtime)
1196 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1202 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1204 meshlink_errno = MESHLINK_ESTORAGE;
1210 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1212 // Remove the key if there are no outstanding invitations.
1215 if(mesh->invitation_key) {
1216 ecdsa_free(mesh->invitation_key);
1217 mesh->invitation_key = NULL;
1221 if(mesh->invitation_key)
1224 // Create a new key if necessary.
1225 FILE *f = fopen(filename, "r");
1227 if(errno != ENOENT) {
1228 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1229 meshlink_errno = MESHLINK_ESTORAGE;
1233 mesh->invitation_key = ecdsa_generate();
1234 if(!mesh->invitation_key) {
1235 fprintf(stderr, "Could not generate a new key!\n");
1236 meshlink_errno = MESHLINK_EINTERNAL;
1239 f = fopen(filename, "w");
1241 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1242 meshlink_errno = MESHLINK_ESTORAGE;
1245 chmod(filename, 0600);
1246 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1249 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1251 if(!mesh->invitation_key) {
1252 fprintf(stderr, "Could not read private key from %s\n", filename);
1253 meshlink_errno = MESHLINK_ESTORAGE;
1257 return mesh->invitation_key;
1260 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1261 if(!mesh || !address) {
1262 meshlink_errno = MESHLINK_EINVAL;
1266 for(const char *p = address; *p; p++) {
1267 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1269 fprintf(stderr, "Invalid character in address: %s\n", address);
1270 meshlink_errno = MESHLINK_EINVAL;
1274 return append_config_file(mesh, mesh->self->name, "Address", address);
1277 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1279 meshlink_errno = MESHLINK_EINVAL;
1283 // Check validity of the new node's name
1284 if(!check_id(name)) {
1285 fprintf(stderr, "Invalid name for node.\n");
1286 meshlink_errno = MESHLINK_EINVAL;
1290 // Ensure no host configuration file with that name exists
1291 char filename[PATH_MAX];
1292 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1293 if(!access(filename, F_OK)) {
1294 fprintf(stderr, "A host config file for %s already exists!\n", name);
1295 meshlink_errno = MESHLINK_EEXIST;
1299 // Ensure no other nodes know about this name
1300 if(meshlink_get_node(mesh, name)) {
1301 fprintf(stderr, "A node with name %s is already known!\n", name);
1302 meshlink_errno = MESHLINK_EEXIST;
1306 // Get the local address
1307 char *address = get_my_hostname(mesh);
1309 fprintf(stderr, "No Address known for ourselves!\n");
1310 meshlink_errno = MESHLINK_ERESOLV;
1314 if(!refresh_invitation_key(mesh)) {
1315 meshlink_errno = MESHLINK_EINTERNAL;
1321 // Create a hash of the key.
1322 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1323 sha512(fingerprint, strlen(fingerprint), hash);
1324 b64encode_urlsafe(hash, hash, 18);
1326 // Create a random cookie for this invitation.
1328 randomize(cookie, 18);
1330 // Create a filename that doesn't reveal the cookie itself
1331 char buf[18 + strlen(fingerprint)];
1332 char cookiehash[64];
1333 memcpy(buf, cookie, 18);
1334 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1335 sha512(buf, sizeof buf, cookiehash);
1336 b64encode_urlsafe(cookiehash, cookiehash, 18);
1338 b64encode_urlsafe(cookie, cookie, 18);
1342 // Create a file containing the details of the invitation.
1343 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1344 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1346 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1347 meshlink_errno = MESHLINK_ESTORAGE;
1350 FILE *f = fdopen(ifd, "w");
1354 // Fill in the details.
1355 fprintf(f, "Name = %s\n", name);
1357 // fprintf(f, "NetName = %s\n", netname);
1358 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1360 // Copy Broadcast and Mode
1361 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1362 FILE *tc = fopen(filename, "r");
1365 while(fgets(buf, sizeof buf, tc)) {
1366 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1367 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1369 // Make sure there is a newline character.
1370 if(!strchr(buf, '\n'))
1376 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1377 meshlink_errno = MESHLINK_ESTORAGE;
1381 fprintf(f, "#---------------------------------------------------------------#\n");
1382 fprintf(f, "Name = %s\n", mesh->self->name);
1384 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1388 // Create an URL from the local address, key hash and cookie
1390 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1396 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1397 if(!mesh || !invitation) {
1398 meshlink_errno = MESHLINK_EINVAL;
1402 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1403 char copy[strlen(invitation) + 1];
1404 strcpy(copy, invitation);
1406 // Split the invitation URL into hostname, port, key hash and cookie.
1408 char *slash = strchr(copy, '/');
1414 if(strlen(slash) != 48)
1417 char *address = copy;
1419 if(*address == '[') {
1421 char *bracket = strchr(address, ']');
1425 if(bracket[1] == ':')
1428 port = strchr(address, ':');
1436 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1439 // Generate a throw-away key for the invitation.
1440 ecdsa_t *key = ecdsa_generate();
1442 meshlink_errno = MESHLINK_EINTERNAL;
1446 char *b64key = ecdsa_get_base64_public_key(key);
1448 //Before doing meshlink_join make sure we are not connected to another mesh
1449 if ( mesh->threadstarted ){
1453 // Connect to the meshlink daemon mentioned in the URL.
1454 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1456 meshlink_errno = MESHLINK_ERESOLV;
1460 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1461 if(mesh->sock <= 0) {
1462 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1464 meshlink_errno = MESHLINK_ENETWORK;
1468 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1469 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1470 closesocket(mesh->sock);
1472 meshlink_errno = MESHLINK_ENETWORK;
1478 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1480 // Tell him we have an invitation, and give him our throw-away key.
1484 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1485 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1486 closesocket(mesh->sock);
1487 meshlink_errno = MESHLINK_ENETWORK;
1493 char hisname[4096] = "";
1494 int code, hismajor, hisminor = 0;
1496 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) {
1497 fprintf(stderr, "Cannot read greeting from peer\n");
1498 closesocket(mesh->sock);
1499 meshlink_errno = MESHLINK_ENETWORK;
1503 // Check if the hash of the key he gave us matches the hash in the URL.
1504 char *fingerprint = mesh->line + 2;
1506 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1507 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1508 meshlink_errno = MESHLINK_EINTERNAL;
1511 if(memcmp(hishash, mesh->hash, 18)) {
1512 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1513 meshlink_errno = MESHLINK_EPEER;
1518 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1520 meshlink_errno = MESHLINK_EINTERNAL;
1524 // Start an SPTPS session
1525 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1526 meshlink_errno = MESHLINK_EINTERNAL;
1530 // Feed rest of input buffer to SPTPS
1531 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1532 meshlink_errno = MESHLINK_EPEER;
1538 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1542 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1543 meshlink_errno = MESHLINK_ENETWORK;
1547 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1548 meshlink_errno = MESHLINK_EPEER;
1553 sptps_stop(&mesh->sptps);
1556 closesocket(mesh->sock);
1558 if(!mesh->success) {
1559 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1560 meshlink_errno = MESHLINK_EPEER;
1567 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1568 meshlink_errno = MESHLINK_EINVAL;
1572 char *meshlink_export(meshlink_handle_t *mesh) {
1574 meshlink_errno = MESHLINK_EINVAL;
1578 char filename[PATH_MAX];
1579 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1580 FILE *f = fopen(filename, "r");
1582 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1583 meshlink_errno = MESHLINK_ESTORAGE;
1587 fseek(f, 0, SEEK_END);
1588 int fsize = ftell(f);
1591 size_t len = fsize + 9 + strlen(mesh->self->name);
1592 char *buf = xmalloc(len);
1593 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1594 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1595 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1597 meshlink_errno = MESHLINK_ESTORAGE;
1606 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1607 if(!mesh || !data) {
1608 meshlink_errno = MESHLINK_EINVAL;
1612 if(strncmp(data, "Name = ", 7)) {
1613 fprintf(stderr, "Invalid data\n");
1614 meshlink_errno = MESHLINK_EPEER;
1618 char *end = strchr(data + 7, '\n');
1620 fprintf(stderr, "Invalid data\n");
1621 meshlink_errno = MESHLINK_EPEER;
1625 int len = end - (data + 7);
1627 memcpy(name, data + 7, len);
1629 if(!check_id(name)) {
1630 fprintf(stderr, "Invalid Name\n");
1631 meshlink_errno = MESHLINK_EPEER;
1635 char filename[PATH_MAX];
1636 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1637 if(!access(filename, F_OK)) {
1638 fprintf(stderr, "File %s already exists, not importing\n", filename);
1639 meshlink_errno = MESHLINK_EEXIST;
1643 if(errno != ENOENT) {
1644 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1645 meshlink_errno = MESHLINK_ESTORAGE;
1649 FILE *f = fopen(filename, "w");
1651 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1652 meshlink_errno = MESHLINK_ESTORAGE;
1656 fwrite(end + 1, strlen(end + 1), 1, f);
1659 load_all_nodes(mesh);
1664 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1665 if(!mesh || !node) {
1666 meshlink_errno = MESHLINK_EINVAL;
1672 n->status.blacklisted=true;
1673 fprintf(stderr, "Blacklisted %s.\n",node->name);
1675 //Make blacklisting persistent in the config file
1676 append_config_file(mesh, n->name, "blacklisted", "yes");
1681 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1682 if(!mesh || !node) {
1683 meshlink_errno = MESHLINK_EINVAL;
1687 node_t *n = (node_t *)node;
1688 n->status.blacklisted = false;
1690 //TODO: remove blacklisted = yes from the config file
1695 /* Hint that a hostname may be found at an address
1696 * See header file for detailed comment.
1698 extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, struct sockaddr *addr) {
1699 if(!mesh || !node || !addr)
1702 char *addr_str = malloc(MAX_ADDRESS_LENGTH*sizeof(char));
1703 memset(addr_str, 0, MAX_ADDRESS_LENGTH*sizeof(char));
1705 char *port_str = malloc(MAX_PORT_LENGTH*sizeof(char));
1706 memset(port_str, 0, MAX_PORT_LENGTH*sizeof(char));
1708 // extra byte for a space, and one to make sure string is null-terminated
1709 int full_addr_len = MAX_ADDRESS_LENGTH + MAX_PORT_LENGTH + 2;
1711 char *full_addr_str = malloc(full_addr_len*sizeof(char));
1712 memset(full_addr_str, 0, full_addr_len*sizeof(char));
1714 // get address and port number
1715 if(!get_ip_str(addr, addr_str, MAX_ADDRESS_LENGTH))
1717 if(!get_port_str(addr, port_str, MAX_ADDRESS_LENGTH))
1720 // append_config_file expects an address, a space, and then a port number
1721 strcat(full_addr_str, addr_str);
1722 strcat(full_addr_str, " ");
1723 strcat(full_addr_str, port_str);
1725 append_config_file(mesh, node->name, "Address", full_addr_str);
1730 free(full_addr_str);
1732 // @TODO do we want to fire off a connection attempt right away?
1735 static void __attribute__((constructor)) meshlink_init(void) {
1739 static void __attribute__((destructor)) meshlink_exit(void) {