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 __thread meshlink_errno_t meshlink_errno;
52 //TODO: this can go away completely
53 const var_t variables[] = {
54 /* Server configuration */
55 {"AddressFamily", VAR_SERVER},
56 {"AutoConnect", VAR_SERVER | VAR_SAFE},
57 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
58 {"BindToInterface", VAR_SERVER},
59 {"Broadcast", VAR_SERVER | VAR_SAFE},
60 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
61 {"DecrementTTL", VAR_SERVER},
62 {"Device", VAR_SERVER},
63 {"DeviceType", VAR_SERVER},
64 {"DirectOnly", VAR_SERVER},
65 {"ECDSAPrivateKeyFile", VAR_SERVER},
66 {"ExperimentalProtocol", VAR_SERVER},
67 {"Forwarding", VAR_SERVER},
68 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
69 {"Hostnames", VAR_SERVER},
70 {"IffOneQueue", VAR_SERVER},
71 {"Interface", VAR_SERVER},
72 {"KeyExpire", VAR_SERVER},
73 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
74 {"LocalDiscovery", VAR_SERVER},
75 {"MACExpire", VAR_SERVER},
76 {"MaxConnectionBurst", VAR_SERVER},
77 {"MaxOutputBufferSize", VAR_SERVER},
78 {"MaxTimeout", VAR_SERVER},
79 {"Mode", VAR_SERVER | VAR_SAFE},
81 {"PingInterval", VAR_SERVER},
82 {"PingTimeout", VAR_SERVER},
83 {"PriorityInheritance", VAR_SERVER},
84 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
85 {"PrivateKeyFile", VAR_SERVER},
86 {"ProcessPriority", VAR_SERVER},
87 {"Proxy", VAR_SERVER},
88 {"ReplayWindow", VAR_SERVER},
89 {"ScriptsExtension", VAR_SERVER},
90 {"ScriptsInterpreter", VAR_SERVER},
91 {"StrictSubnets", VAR_SERVER},
92 {"TunnelServer", VAR_SERVER},
93 {"VDEGroup", VAR_SERVER},
94 {"VDEPort", VAR_SERVER},
95 /* Host configuration */
96 {"Address", VAR_HOST | VAR_MULTIPLE},
97 {"Cipher", VAR_SERVER | VAR_HOST},
98 {"ClampMSS", VAR_SERVER | VAR_HOST},
99 {"Compression", VAR_SERVER | VAR_HOST},
100 {"Digest", VAR_SERVER | VAR_HOST},
101 {"ECDSAPublicKey", VAR_HOST},
102 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
103 {"IndirectData", VAR_SERVER | VAR_HOST},
104 {"MACLength", VAR_SERVER | VAR_HOST},
105 {"PMTU", VAR_SERVER | VAR_HOST},
106 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
108 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
109 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
110 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
111 {"TCPOnly", VAR_SERVER | VAR_HOST},
112 {"Weight", VAR_HOST | VAR_SAFE},
116 static bool fcopy(FILE *out, const char *filename) {
117 FILE *in = fopen(filename, "r");
119 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
125 while((len = fread(buf, 1, sizeof buf, in)))
126 fwrite(buf, len, 1, out);
131 static int rstrip(char *value) {
132 int len = strlen(value);
133 while(len && strchr("\t\r\n ", value[len - 1]))
138 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
140 if(!filename || (*hostname && *port))
143 FILE *f = fopen(filename, "r");
147 while(fgets(line, sizeof line, f)) {
151 p += strcspn(p, "\t =");
154 q = p + strspn(p, "\t ");
156 q += 1 + strspn(q + 1, "\t ");
158 p = q + strcspn(q, "\t ");
161 p += strspn(p, "\t ");
162 p[strcspn(p, "\t ")] = 0;
164 if(!*port && !strcasecmp(line, "Port")) {
166 } else if(!*hostname && !strcasecmp(line, "Address")) {
167 *hostname = xstrdup(q);
174 if(*hostname && *port)
180 static char *get_my_hostname(meshlink_handle_t* mesh) {
181 char *hostname = NULL;
183 char *hostport = NULL;
184 char *name = mesh->self->name;
185 char filename[PATH_MAX] = "";
189 // Use first Address statement in own host config file
190 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
191 scan_for_hostname(filename, &hostname, &port);
196 // If that doesn't work, guess externally visible hostname
197 fprintf(stderr, "Trying to discover externally visible hostname...\n");
198 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
199 struct addrinfo *aip = ai;
200 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
203 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
205 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
211 send(s, request, sizeof request - 1, 0);
212 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
215 if(line[len - 1] == '\n')
217 char *p = strrchr(line, '\n');
219 hostname = xstrdup(p + 1);
232 // Check that the hostname is reasonable
234 for(char *p = hostname; *p; p++) {
235 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
237 // If not, forget it.
247 f = fopen(filename, "a");
249 fprintf(f, "\nAddress = %s\n", hostname);
252 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
257 if(strchr(hostname, ':'))
258 xasprintf(&hostport, "[%s]:%s", hostname, port);
260 xasprintf(&hostport, "%s:%s", hostname, port);
262 if(strchr(hostname, ':'))
263 xasprintf(&hostport, "[%s]", hostname);
265 hostport = xstrdup(hostname);
273 static char *get_line(const char **data) {
282 static char line[1024];
283 const char *end = strchr(*data, '\n');
284 size_t len = end ? end - *data : strlen(*data);
285 if(len >= sizeof line) {
286 fprintf(stderr, "Maximum line length exceeded!\n");
289 if(len && !isprint(**data))
292 memcpy(line, *data, len);
303 static char *get_value(const char *data, const char *var) {
304 char *line = get_line(&data);
308 char *sep = line + strcspn(line, " \t=");
309 char *val = sep + strspn(sep, " \t");
311 val += 1 + strspn(val + 1, " \t");
313 if(strcasecmp(line, var))
318 static bool try_bind(int port) {
319 struct addrinfo *ai = NULL;
320 struct addrinfo hint = {
321 .ai_flags = AI_PASSIVE,
322 .ai_family = AF_UNSPEC,
323 .ai_socktype = SOCK_STREAM,
324 .ai_protocol = IPPROTO_TCP,
328 snprintf(portstr, sizeof portstr, "%d", port);
330 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
334 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
339 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
352 static int check_port(meshlink_handle_t *mesh) {
353 for(int i = 0; i < 1000; i++) {
354 int port = 0x1000 + (rand() & 0x7fff);
356 char filename[PATH_MAX];
357 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
358 FILE *f = fopen(filename, "a");
360 fprintf(stderr, "Please change MeshLink's Port manually.\n");
364 fprintf(f, "Port = %d\n", port);
370 fprintf(stderr, "Please change MeshLink's Port manually.\n");
374 static bool finalize_join(meshlink_handle_t *mesh) {
375 char *name = xstrdup(get_value(mesh->data, "Name"));
377 fprintf(stderr, "No Name found in invitation!\n");
381 if(!check_id(name)) {
382 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
386 char filename[PATH_MAX];
387 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
389 FILE *f = fopen(filename, "w");
391 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
395 fprintf(f, "Name = %s\n", name);
397 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
398 FILE *fh = fopen(filename, "w");
400 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
405 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
406 // Other chunks go unfiltered to their respective host config files
407 const char *p = mesh->data;
410 while((l = get_line(&p))) {
415 // Split line into variable and value
416 int len = strcspn(l, "\t =");
418 value += strspn(value, "\t ");
421 value += strspn(value, "\t ");
426 if(!strcasecmp(l, "Name"))
427 if(strcmp(value, name))
431 else if(!strcasecmp(l, "NetName"))
434 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
437 for(i = 0; variables[i].name; i++) {
438 if(strcasecmp(l, variables[i].name))
444 // Ignore unknown and unsafe variables
446 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
448 } else if(!(variables[i].type & VAR_SAFE)) {
449 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
453 // Copy the safe variable to the right config file
454 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
459 while(l && !strcasecmp(l, "Name")) {
460 if(!check_id(value)) {
461 fprintf(stderr, "Invalid Name found in invitation.\n");
465 if(!strcmp(value, name)) {
466 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
470 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
471 f = fopen(filename, "w");
474 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
478 while((l = get_line(&p))) {
479 if(!strcmp(l, "#---------------------------------------------------------------#"))
481 int len = strcspn(l, "\t =");
482 if(len == 4 && !strncasecmp(l, "Name", 4)) {
484 value += strspn(value, "\t ");
487 value += strspn(value, "\t ");
500 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
504 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
505 fprintf(fh, "Port = %s\n", mesh->myport);
509 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
512 free(mesh->self->name);
513 free(mesh->self->connection->name);
514 mesh->self->name = xstrdup(name);
515 mesh->self->connection->name = name;
517 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
519 load_all_nodes(mesh);
524 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
525 meshlink_handle_t* mesh = handle;
527 int result = send(mesh->sock, data, len, 0);
528 if(result == -1 && errno == EINTR)
538 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
539 meshlink_handle_t* mesh = handle;
541 case SPTPS_HANDSHAKE:
542 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
545 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
546 memcpy(mesh->data + mesh->thedatalen, msg, len);
547 mesh->thedatalen += len;
548 mesh->data[mesh->thedatalen] = 0;
552 return finalize_join(mesh);
555 fprintf(stderr, "Invitation succesfully accepted.\n");
556 shutdown(mesh->sock, SHUT_RDWR);
557 mesh->success = true;
567 static bool recvline(meshlink_handle_t* mesh, size_t len) {
568 char *newline = NULL;
573 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
574 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
575 if(result == -1 && errno == EINTR)
579 mesh->blen += result;
582 if(newline - mesh->buffer >= len)
585 len = newline - mesh->buffer;
587 memcpy(mesh->line, mesh->buffer, len);
589 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
590 mesh->blen -= len + 1;
594 static bool sendline(int fd, char *format, ...) {
595 static char buffer[4096];
600 va_start(ap, format);
601 blen = vsnprintf(buffer, sizeof buffer, format, ap);
604 if(blen < 1 || blen >= sizeof buffer)
611 int result = send(fd, p, blen, MSG_NOSIGNAL);
612 if(result == -1 && errno == EINTR)
623 static const char *errstr[] = {
624 [MESHLINK_OK] = "No error",
625 [MESHLINK_EINVAL] = "Invalid argument",
626 [MESHLINK_ENOMEM] = "Out of memory",
627 [MESHLINK_ENOENT] = "No such node",
628 [MESHLINK_EEXIST] = "Node already exists",
629 [MESHLINK_EINTERNAL] = "Internal error",
630 [MESHLINK_ERESOLV] = "Could not resolve hostname",
631 [MESHLINK_ESTORAGE] = "Storage error",
632 [MESHLINK_ENETWORK] = "Network error",
633 [MESHLINK_EPEER] = "Error communicating with peer",
636 const char *meshlink_strerror(meshlink_errno_t err) {
637 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
638 return "Invalid error code";
642 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
645 char pubname[PATH_MAX], privname[PATH_MAX];
647 fprintf(stderr, "Generating ECDSA keypair:\n");
649 if(!(key = ecdsa_generate())) {
650 fprintf(stderr, "Error during key generation!\n");
651 meshlink_errno = MESHLINK_EINTERNAL;
654 fprintf(stderr, "Done.\n");
656 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
657 f = fopen(privname, "w");
660 meshlink_errno = MESHLINK_ESTORAGE;
665 fchmod(fileno(f), 0600);
668 if(!ecdsa_write_pem_private_key(key, f)) {
669 fprintf(stderr, "Error writing private key!\n");
672 meshlink_errno = MESHLINK_EINTERNAL;
678 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
679 f = fopen(pubname, "a");
682 meshlink_errno = MESHLINK_ESTORAGE;
686 char *pubkey = ecdsa_get_base64_public_key(key);
687 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
696 static bool meshlink_setup(meshlink_handle_t *mesh) {
697 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
698 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
699 meshlink_errno = MESHLINK_ESTORAGE;
703 char filename[PATH_MAX];
704 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
706 if(mkdir(filename, 0777) && errno != EEXIST) {
707 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
708 meshlink_errno = MESHLINK_ESTORAGE;
712 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
714 if(!access(filename, F_OK)) {
715 fprintf(stderr, "Configuration file %s already exists!\n", filename);
716 meshlink_errno = MESHLINK_EEXIST;
720 FILE *f = fopen(filename, "w");
722 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
723 meshlink_errno = MESHLINK_ESTORAGE;
727 fprintf(f, "Name = %s\n", mesh->name);
730 if(!ecdsa_keygen(mesh)) {
731 meshlink_errno = MESHLINK_EINTERNAL;
740 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char* appname) {
741 return meshlink_open_with_size(confbase, name, appname, sizeof(meshlink_handle_t));
744 meshlink_handle_t *meshlink_open_with_size(const char *confbase, const char *name, const char* appname, size_t size) {
746 // Validate arguments provided by the application
747 bool usingname = false;
749 if(!confbase || !*confbase) {
750 fprintf(stderr, "No confbase given!\n");
751 meshlink_errno = MESHLINK_EINVAL;
755 if(!appname || !*appname) {
756 fprintf(stderr, "No appname given!\n");
757 meshlink_errno = MESHLINK_EINVAL;
761 if(!name || !*name) {
762 fprintf(stderr, "No name given!\n");
765 else { //check name only if there is a name != NULL
767 if(!check_id(name)) {
768 fprintf(stderr, "Invalid name given!\n");
769 meshlink_errno = MESHLINK_EINVAL;
771 } else { usingname = true;}
774 meshlink_handle_t *mesh = xzalloc(size);
775 mesh->confbase = xstrdup(confbase);
776 mesh->appname = xstrdup(appname);
777 if (usingname) mesh->name = xstrdup(name);
778 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
779 mesh->threadstarted = false;
780 event_loop_init(&mesh->loop);
781 mesh->loop.data = mesh;
783 // TODO: should be set by a function.
784 mesh->debug_level = 5;
786 // Check whether meshlink.conf already exists
788 char filename[PATH_MAX];
789 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
791 if(access(filename, R_OK)) {
792 if(errno == ENOENT) {
794 if(!meshlink_setup(mesh)) {
795 // meshlink_errno is set by meshlink_setup()
799 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
800 meshlink_close(mesh);
801 meshlink_errno = MESHLINK_ESTORAGE;
806 // Read the configuration
808 init_configuration(&mesh->config);
810 if(!read_server_config(mesh)) {
811 meshlink_close(mesh);
812 meshlink_errno = MESHLINK_ESTORAGE;
817 struct WSAData wsa_state;
818 WSAStartup(MAKEWORD(2, 2), &wsa_state);
821 // Setup up everything
822 // TODO: we should not open listening sockets yet
824 if(!setup_network(mesh)) {
825 meshlink_close(mesh);
826 meshlink_errno = MESHLINK_ENETWORK;
833 static void *meshlink_main_loop(void *arg) {
834 meshlink_handle_t *mesh = arg;
836 try_outgoing_connections(mesh);
838 fprintf(stderr, "Starting main_loop...\n");
840 fprintf(stderr, "main_loop returned.\n");
845 bool meshlink_start(meshlink_handle_t *mesh) {
847 fprintf(stderr, "meshlink_start called\n");
850 meshlink_errno = MESHLINK_EINVAL;
854 // TODO: open listening sockets first
856 //Check that a valid name is set
858 fprintf(stderr, "No name given!\n");
859 meshlink_errno = MESHLINK_EINVAL;
863 // Start the main thread
865 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
866 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
867 memset(&mesh->thread, 0, sizeof mesh->thread);
868 meshlink_errno = MESHLINK_EINTERNAL;
872 mesh->threadstarted=true;
875 if(!discovery_start(mesh))
881 void meshlink_stop(meshlink_handle_t *mesh) {
883 fprintf(stderr, "meshlink_stop called\n");
886 meshlink_errno = MESHLINK_EINVAL;
891 discovery_stop(mesh);
893 // Shut down a listening socket to signal the main thread to shut down
895 listen_socket_t *s = &mesh->listen_socket[0];
896 shutdown(s->tcp.fd, SHUT_RDWR);
898 // Wait for the main thread to finish
900 pthread_join(mesh->thread, NULL);
901 mesh->threadstarted = false;
905 closesocket(s->tcp.fd);
906 io_del(&mesh->loop, &s->tcp);
907 s->tcp.fd = setup_listen_socket(&s->sa);
909 logger(DEBUG_ALWAYS, LOG_ERR, "Could not repair listenen socket!");
911 io_add(&mesh->loop, &s->tcp, handle_new_meta_connection, s, s->tcp.fd, IO_READ);
914 void meshlink_close(meshlink_handle_t *mesh) {
915 if(!mesh || !mesh->confbase) {
916 meshlink_errno = MESHLINK_EINVAL;
920 // Close and free all resources used.
922 close_network_connections(mesh);
924 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
926 exit_configuration(&mesh->config);
927 event_loop_exit(&mesh->loop);
934 ecdsa_free(mesh->invitation_key);
937 free(mesh->confbase);
939 memset(mesh, 0, sizeof *mesh);
944 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
946 meshlink_errno = MESHLINK_EINVAL;
950 mesh->receive_cb = cb;
953 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
955 meshlink_errno = MESHLINK_EINVAL;
959 mesh->node_status_cb = cb;
962 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
964 meshlink_errno = MESHLINK_EINVAL;
969 mesh->log_level = level;
972 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
973 if(!mesh || !destination) {
974 meshlink_errno = MESHLINK_EINVAL;
982 meshlink_errno = MESHLINK_EINVAL;
986 //add packet to the queue
987 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
988 packet_in_queue->destination=destination;
989 packet_in_queue->data=data;
990 packet_in_queue->len=len;
991 if(!meshlink_queue_push(&mesh->outpacketqueue, packet_in_queue)) {
992 free(packet_in_queue);
997 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
1001 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
1002 vpn_packet_t packet;
1003 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
1005 outpacketqueue_t* p = meshlink_queue_pop(&mesh->outpacketqueue);
1009 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
1014 packet.probe = false;
1015 memset(hdr, 0, sizeof *hdr);
1016 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1017 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1019 packet.len = sizeof *hdr + p->len;
1020 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1022 mesh->self->in_packets++;
1023 mesh->self->in_bytes += packet.len;
1024 route(mesh, mesh->self, &packet);
1028 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1029 if(!mesh || !destination) {
1030 meshlink_errno = MESHLINK_EINVAL;
1034 node_t *n = (node_t *)destination;
1035 if(!n->status.reachable)
1037 else if(n->mtuprobes > 30 && n->minmtu)
1043 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1044 if(!mesh || !node) {
1045 meshlink_errno = MESHLINK_EINVAL;
1049 node_t *n = (node_t *)node;
1051 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1052 meshlink_errno = MESHLINK_EINTERNAL;
1056 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1059 meshlink_errno = MESHLINK_EINTERNAL;
1064 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1065 if(!mesh || !name) {
1066 meshlink_errno = MESHLINK_EINVAL;
1070 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1073 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1074 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1075 meshlink_errno = MESHLINK_EINVAL;
1079 meshlink_node_t **result;
1082 pthread_mutex_lock(&(mesh->nodes_mutex));
1084 *nmemb = mesh->nodes->count;
1085 result = realloc(nodes, *nmemb * sizeof *nodes);
1088 meshlink_node_t **p = result;
1089 for splay_each(node_t, n, mesh->nodes)
1090 *p++ = (meshlink_node_t *)n;
1094 meshlink_errno = MESHLINK_ENOMEM;
1097 pthread_mutex_unlock(&(mesh->nodes_mutex));
1102 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1103 if(!mesh || !data || !len || !signature || !siglen) {
1104 meshlink_errno = MESHLINK_EINVAL;
1108 if(*siglen < MESHLINK_SIGLEN) {
1109 meshlink_errno = MESHLINK_EINVAL;
1113 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1114 meshlink_errno = MESHLINK_EINTERNAL;
1118 *siglen = MESHLINK_SIGLEN;
1122 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1123 if(!mesh || !data || !len || !signature) {
1124 meshlink_errno = MESHLINK_EINVAL;
1128 if(siglen != MESHLINK_SIGLEN) {
1129 meshlink_errno = MESHLINK_EINVAL;
1133 struct node_t *n = (struct node_t *)source;
1134 node_read_ecdsa_public_key(mesh, n);
1136 meshlink_errno = MESHLINK_EINTERNAL;
1140 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1143 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1144 char filename[PATH_MAX];
1146 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1147 if(mkdir(filename, 0700) && errno != EEXIST) {
1148 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1149 meshlink_errno = MESHLINK_ESTORAGE;
1153 // Count the number of valid invitations, clean up old ones
1154 DIR *dir = opendir(filename);
1156 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1157 meshlink_errno = MESHLINK_ESTORAGE;
1164 time_t deadline = time(NULL) - 604800; // 1 week in the past
1166 while((ent = readdir(dir))) {
1167 if(strlen(ent->d_name) != 24)
1169 char invname[PATH_MAX];
1171 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1172 if(!stat(invname, &st)) {
1173 if(mesh->invitation_key && deadline < st.st_mtime)
1178 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1184 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1186 meshlink_errno = MESHLINK_ESTORAGE;
1192 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1194 // Remove the key if there are no outstanding invitations.
1197 if(mesh->invitation_key) {
1198 ecdsa_free(mesh->invitation_key);
1199 mesh->invitation_key = NULL;
1203 if(mesh->invitation_key)
1206 // Create a new key if necessary.
1207 FILE *f = fopen(filename, "r");
1209 if(errno != ENOENT) {
1210 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1211 meshlink_errno = MESHLINK_ESTORAGE;
1215 mesh->invitation_key = ecdsa_generate();
1216 if(!mesh->invitation_key) {
1217 fprintf(stderr, "Could not generate a new key!\n");
1218 meshlink_errno = MESHLINK_EINTERNAL;
1221 f = fopen(filename, "w");
1223 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1224 meshlink_errno = MESHLINK_ESTORAGE;
1227 chmod(filename, 0600);
1228 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1231 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1233 if(!mesh->invitation_key) {
1234 fprintf(stderr, "Could not read private key from %s\n", filename);
1235 meshlink_errno = MESHLINK_ESTORAGE;
1239 return mesh->invitation_key;
1242 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1243 if(!mesh || !address) {
1244 meshlink_errno = MESHLINK_EINVAL;
1248 for(const char *p = address; *p; p++) {
1249 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1251 fprintf(stderr, "Invalid character in address: %s\n", address);
1252 meshlink_errno = MESHLINK_EINVAL;
1256 return append_config_file(mesh, mesh->self->name, "Address", address);
1259 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1261 meshlink_errno = MESHLINK_EINVAL;
1265 // Check validity of the new node's name
1266 if(!check_id(name)) {
1267 fprintf(stderr, "Invalid name for node.\n");
1268 meshlink_errno = MESHLINK_EINVAL;
1272 // Ensure no host configuration file with that name exists
1273 char filename[PATH_MAX];
1274 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1275 if(!access(filename, F_OK)) {
1276 fprintf(stderr, "A host config file for %s already exists!\n", name);
1277 meshlink_errno = MESHLINK_EEXIST;
1281 // Ensure no other nodes know about this name
1282 if(meshlink_get_node(mesh, name)) {
1283 fprintf(stderr, "A node with name %s is already known!\n", name);
1284 meshlink_errno = MESHLINK_EEXIST;
1288 // Get the local address
1289 char *address = get_my_hostname(mesh);
1291 fprintf(stderr, "No Address known for ourselves!\n");
1292 meshlink_errno = MESHLINK_ERESOLV;
1296 if(!refresh_invitation_key(mesh)) {
1297 meshlink_errno = MESHLINK_EINTERNAL;
1303 // Create a hash of the key.
1304 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1305 sha512(fingerprint, strlen(fingerprint), hash);
1306 b64encode_urlsafe(hash, hash, 18);
1308 // Create a random cookie for this invitation.
1310 randomize(cookie, 18);
1312 // Create a filename that doesn't reveal the cookie itself
1313 char buf[18 + strlen(fingerprint)];
1314 char cookiehash[64];
1315 memcpy(buf, cookie, 18);
1316 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1317 sha512(buf, sizeof buf, cookiehash);
1318 b64encode_urlsafe(cookiehash, cookiehash, 18);
1320 b64encode_urlsafe(cookie, cookie, 18);
1324 // Create a file containing the details of the invitation.
1325 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1326 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1328 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1329 meshlink_errno = MESHLINK_ESTORAGE;
1332 FILE *f = fdopen(ifd, "w");
1336 // Fill in the details.
1337 fprintf(f, "Name = %s\n", name);
1339 // fprintf(f, "NetName = %s\n", netname);
1340 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1342 // Copy Broadcast and Mode
1343 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1344 FILE *tc = fopen(filename, "r");
1347 while(fgets(buf, sizeof buf, tc)) {
1348 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1349 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1351 // Make sure there is a newline character.
1352 if(!strchr(buf, '\n'))
1358 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1359 meshlink_errno = MESHLINK_ESTORAGE;
1363 fprintf(f, "#---------------------------------------------------------------#\n");
1364 fprintf(f, "Name = %s\n", mesh->self->name);
1366 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1370 // Create an URL from the local address, key hash and cookie
1372 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1378 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1379 if(!mesh || !invitation) {
1380 meshlink_errno = MESHLINK_EINVAL;
1384 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1385 char copy[strlen(invitation) + 1];
1386 strcpy(copy, invitation);
1388 // Split the invitation URL into hostname, port, key hash and cookie.
1390 char *slash = strchr(copy, '/');
1396 if(strlen(slash) != 48)
1399 char *address = copy;
1401 if(*address == '[') {
1403 char *bracket = strchr(address, ']');
1407 if(bracket[1] == ':')
1410 port = strchr(address, ':');
1418 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1421 // Generate a throw-away key for the invitation.
1422 ecdsa_t *key = ecdsa_generate();
1424 meshlink_errno = MESHLINK_EINTERNAL;
1428 char *b64key = ecdsa_get_base64_public_key(key);
1430 //Before doing meshlink_join make sure we are not connected to another mesh
1431 if ( mesh->threadstarted ){
1435 // Connect to the meshlink daemon mentioned in the URL.
1436 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1438 meshlink_errno = MESHLINK_ERESOLV;
1442 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1443 if(mesh->sock <= 0) {
1444 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1446 meshlink_errno = MESHLINK_ENETWORK;
1450 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1451 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1452 closesocket(mesh->sock);
1454 meshlink_errno = MESHLINK_ENETWORK;
1460 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1462 // Tell him we have an invitation, and give him our throw-away key.
1466 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1467 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1468 closesocket(mesh->sock);
1469 meshlink_errno = MESHLINK_ENETWORK;
1475 char hisname[4096] = "";
1476 int code, hismajor, hisminor = 0;
1478 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) {
1479 fprintf(stderr, "Cannot read greeting from peer\n");
1480 closesocket(mesh->sock);
1481 meshlink_errno = MESHLINK_ENETWORK;
1485 // Check if the hash of the key he gave us matches the hash in the URL.
1486 char *fingerprint = mesh->line + 2;
1488 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1489 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1490 meshlink_errno = MESHLINK_EINTERNAL;
1493 if(memcmp(hishash, mesh->hash, 18)) {
1494 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1495 meshlink_errno = MESHLINK_EPEER;
1500 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1502 meshlink_errno = MESHLINK_EINTERNAL;
1506 // Start an SPTPS session
1507 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1508 meshlink_errno = MESHLINK_EINTERNAL;
1512 // Feed rest of input buffer to SPTPS
1513 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1514 meshlink_errno = MESHLINK_EPEER;
1520 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1524 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1525 meshlink_errno = MESHLINK_ENETWORK;
1529 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1530 meshlink_errno = MESHLINK_EPEER;
1535 sptps_stop(&mesh->sptps);
1538 closesocket(mesh->sock);
1540 if(!mesh->success) {
1541 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1542 meshlink_errno = MESHLINK_EPEER;
1549 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1550 meshlink_errno = MESHLINK_EINVAL;
1554 char *meshlink_export(meshlink_handle_t *mesh) {
1556 meshlink_errno = MESHLINK_EINVAL;
1560 char filename[PATH_MAX];
1561 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1562 FILE *f = fopen(filename, "r");
1564 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1565 meshlink_errno = MESHLINK_ESTORAGE;
1569 fseek(f, 0, SEEK_END);
1570 int fsize = ftell(f);
1573 size_t len = fsize + 9 + strlen(mesh->self->name);
1574 char *buf = xmalloc(len);
1575 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1576 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1577 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1579 meshlink_errno = MESHLINK_ESTORAGE;
1588 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1589 if(!mesh || !data) {
1590 meshlink_errno = MESHLINK_EINVAL;
1594 if(strncmp(data, "Name = ", 7)) {
1595 fprintf(stderr, "Invalid data\n");
1596 meshlink_errno = MESHLINK_EPEER;
1600 char *end = strchr(data + 7, '\n');
1602 fprintf(stderr, "Invalid data\n");
1603 meshlink_errno = MESHLINK_EPEER;
1607 int len = end - (data + 7);
1609 memcpy(name, data + 7, len);
1611 if(!check_id(name)) {
1612 fprintf(stderr, "Invalid Name\n");
1613 meshlink_errno = MESHLINK_EPEER;
1617 char filename[PATH_MAX];
1618 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1619 if(!access(filename, F_OK)) {
1620 fprintf(stderr, "File %s already exists, not importing\n", filename);
1621 meshlink_errno = MESHLINK_EEXIST;
1625 if(errno != ENOENT) {
1626 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1627 meshlink_errno = MESHLINK_ESTORAGE;
1631 FILE *f = fopen(filename, "w");
1633 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1634 meshlink_errno = MESHLINK_ESTORAGE;
1638 fwrite(end + 1, strlen(end + 1), 1, f);
1641 load_all_nodes(mesh);
1646 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1647 if(!mesh || !node) {
1648 meshlink_errno = MESHLINK_EINVAL;
1654 n->status.blacklisted=true;
1655 fprintf(stderr, "Blacklisted %s.\n",node->name);
1657 //Make blacklisting persistent in the config file
1658 append_config_file(mesh, n->name, "blacklisted", "yes");
1663 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1664 if(!mesh || !node) {
1665 meshlink_errno = MESHLINK_EINVAL;
1669 node_t *n = (node_t *)node;
1670 n->status.blacklisted = false;
1672 //TODO: remove blacklisted = yes from the config file
1677 /* Hint that a hostname may be found at an address
1678 * See header file for detailed comment.
1680 extern void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, struct sockaddr *addr) {
1681 if(!mesh || !node || !addr)
1684 char *addr_str = malloc(MAX_ADDRESS_LENGTH*sizeof(char));
1685 memset(addr_str, 0, MAX_ADDRESS_LENGTH*sizeof(char));
1687 char *port_str = malloc(MAX_PORT_LENGTH*sizeof(char));
1688 memset(port_str, 0, MAX_PORT_LENGTH*sizeof(char));
1690 // extra byte for a space, and one to make sure string is null-terminated
1691 int full_addr_len = MAX_ADDRESS_LENGTH + MAX_PORT_LENGTH + 2;
1693 char *full_addr_str = malloc(full_addr_len*sizeof(char));
1694 memset(full_addr_str, 0, full_addr_len*sizeof(char));
1696 // get address and port number
1697 if(!get_ip_str(addr, addr_str, MAX_ADDRESS_LENGTH))
1699 if(!get_port_str(addr, port_str, MAX_ADDRESS_LENGTH))
1702 // append_config_file expects an address, a space, and then a port number
1703 strcat(full_addr_str, addr_str);
1704 strcat(full_addr_str, " ");
1705 strcat(full_addr_str, port_str);
1707 append_config_file(mesh, node->name, "Address", full_addr_str);
1713 free(full_addr_str);
1715 // @TODO do we want to fire off a connection attempt right away?
1718 static void __attribute__((constructor)) meshlink_init(void) {
1722 static void __attribute__((destructor)) meshlink_exit(void) {