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) {
356 fprintf(stderr, "Warning: could not bind to port 655.\n");
358 for(int i = 0; i < 100; 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 fprintf(stderr, "Please change MeshLink's Port manually.\n");
369 fprintf(f, "Port = %d\n", port);
371 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
376 fprintf(stderr, "Please change MeshLink's Port manually.\n");
380 static bool finalize_join(meshlink_handle_t *mesh) {
381 char *name = xstrdup(get_value(mesh->data, "Name"));
383 fprintf(stderr, "No Name found in invitation!\n");
387 if(!check_id(name)) {
388 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
392 char filename[PATH_MAX];
393 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
395 FILE *f = fopen(filename, "w");
397 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
401 fprintf(f, "Name = %s\n", name);
403 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
404 FILE *fh = fopen(filename, "w");
406 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
411 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
412 // Other chunks go unfiltered to their respective host config files
413 const char *p = mesh->data;
416 while((l = get_line(&p))) {
421 // Split line into variable and value
422 int len = strcspn(l, "\t =");
424 value += strspn(value, "\t ");
427 value += strspn(value, "\t ");
432 if(!strcasecmp(l, "Name"))
433 if(strcmp(value, name))
437 else if(!strcasecmp(l, "NetName"))
440 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
443 for(i = 0; variables[i].name; i++) {
444 if(strcasecmp(l, variables[i].name))
450 // Ignore unknown and unsafe variables
452 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
454 } else if(!(variables[i].type & VAR_SAFE)) {
455 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
459 // Copy the safe variable to the right config file
460 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
465 while(l && !strcasecmp(l, "Name")) {
466 if(!check_id(value)) {
467 fprintf(stderr, "Invalid Name found in invitation.\n");
471 if(!strcmp(value, name)) {
472 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
476 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
477 f = fopen(filename, "w");
480 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
484 while((l = get_line(&p))) {
485 if(!strcmp(l, "#---------------------------------------------------------------#"))
487 int len = strcspn(l, "\t =");
488 if(len == 4 && !strncasecmp(l, "Name", 4)) {
490 value += strspn(value, "\t ");
493 value += strspn(value, "\t ");
506 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
510 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
511 fprintf(fh, "Port = %s\n", mesh->myport);
515 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
518 free(mesh->self->name);
519 free(mesh->self->connection->name);
520 mesh->self->name = xstrdup(name);
521 mesh->self->connection->name = name;
523 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
525 load_all_nodes(mesh);
530 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
531 meshlink_handle_t* mesh = handle;
533 int result = send(mesh->sock, data, len, 0);
534 if(result == -1 && errno == EINTR)
544 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
545 meshlink_handle_t* mesh = handle;
547 case SPTPS_HANDSHAKE:
548 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
551 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
552 memcpy(mesh->data + mesh->thedatalen, msg, len);
553 mesh->thedatalen += len;
554 mesh->data[mesh->thedatalen] = 0;
558 return finalize_join(mesh);
561 fprintf(stderr, "Invitation succesfully accepted.\n");
562 shutdown(mesh->sock, SHUT_RDWR);
563 mesh->success = true;
573 static bool recvline(meshlink_handle_t* mesh, size_t len) {
574 char *newline = NULL;
579 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
580 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
581 if(result == -1 && errno == EINTR)
585 mesh->blen += result;
588 if(newline - mesh->buffer >= len)
591 len = newline - mesh->buffer;
593 memcpy(mesh->line, mesh->buffer, len);
595 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
596 mesh->blen -= len + 1;
600 static bool sendline(int fd, char *format, ...) {
601 static char buffer[4096];
606 va_start(ap, format);
607 blen = vsnprintf(buffer, sizeof buffer, format, ap);
610 if(blen < 1 || blen >= sizeof buffer)
617 int result = send(fd, p, blen, MSG_NOSIGNAL);
618 if(result == -1 && errno == EINTR)
629 static const char *errstr[] = {
630 [MESHLINK_OK] = "No error",
631 [MESHLINK_EINVAL] = "Invalid argument",
632 [MESHLINK_ENOMEM] = "Out of memory",
633 [MESHLINK_ENOENT] = "No such node",
634 [MESHLINK_EEXIST] = "Node already exists",
635 [MESHLINK_EINTERNAL] = "Internal error",
636 [MESHLINK_ERESOLV] = "Could not resolve hostname",
637 [MESHLINK_ESTORAGE] = "Storage error",
638 [MESHLINK_ENETWORK] = "Network error",
639 [MESHLINK_EPEER] = "Error communicating with peer",
642 const char *meshlink_strerror(meshlink_errno_t err) {
643 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
644 return "Invalid error code";
648 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
651 char pubname[PATH_MAX], privname[PATH_MAX];
653 fprintf(stderr, "Generating ECDSA keypair:\n");
655 if(!(key = ecdsa_generate())) {
656 fprintf(stderr, "Error during key generation!\n");
657 meshlink_errno = MESHLINK_EINTERNAL;
660 fprintf(stderr, "Done.\n");
662 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
663 f = fopen(privname, "w");
666 meshlink_errno = MESHLINK_ESTORAGE;
671 fchmod(fileno(f), 0600);
674 if(!ecdsa_write_pem_private_key(key, f)) {
675 fprintf(stderr, "Error writing private key!\n");
678 meshlink_errno = MESHLINK_EINTERNAL;
684 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
685 f = fopen(pubname, "a");
688 meshlink_errno = MESHLINK_ESTORAGE;
692 char *pubkey = ecdsa_get_base64_public_key(key);
693 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
702 static bool meshlink_setup(meshlink_handle_t *mesh) {
703 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
704 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
705 meshlink_errno = MESHLINK_ESTORAGE;
709 char filename[PATH_MAX];
710 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
712 if(mkdir(filename, 0777) && errno != EEXIST) {
713 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
714 meshlink_errno = MESHLINK_ESTORAGE;
718 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
720 if(!access(filename, F_OK)) {
721 fprintf(stderr, "Configuration file %s already exists!\n", filename);
722 meshlink_errno = MESHLINK_EEXIST;
726 FILE *f = fopen(filename, "w");
728 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
729 meshlink_errno = MESHLINK_ESTORAGE;
733 fprintf(f, "Name = %s\n", mesh->name);
736 if(!ecdsa_keygen(mesh)) {
737 meshlink_errno = MESHLINK_EINTERNAL;
746 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
747 // Validate arguments provided by the application
748 bool usingname = false;
750 if(!confbase || !*confbase) {
751 fprintf(stderr, "No confbase given!\n");
752 meshlink_errno = MESHLINK_EINVAL;
756 if(!name || !*name) {
757 fprintf(stderr, "No name given!\n");
760 else { //check name only if there is a name != NULL
762 if(!check_id(name)) {
763 fprintf(stderr, "Invalid name given!\n");
764 meshlink_errno = MESHLINK_EINVAL;
766 } else { usingname = true;}
769 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
770 mesh->confbase = xstrdup(confbase);
771 if (usingname) mesh->name = xstrdup(name);
772 pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
773 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
774 mesh->threadstarted = false;
775 event_loop_init(&mesh->loop);
776 mesh->loop.data = mesh;
778 // TODO: should be set by a function.
779 mesh->debug_level = 5;
781 // Check whether meshlink.conf already exists
783 char filename[PATH_MAX];
784 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
786 if(access(filename, R_OK)) {
787 if(errno == ENOENT) {
789 if(!meshlink_setup(mesh)) {
790 // meshlink_errno is set by meshlink_setup()
794 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
795 meshlink_close(mesh);
796 meshlink_errno = MESHLINK_ESTORAGE;
801 // Read the configuration
803 init_configuration(&mesh->config);
805 if(!read_server_config(mesh)) {
806 meshlink_close(mesh);
807 meshlink_errno = MESHLINK_ESTORAGE;
812 struct WSAData wsa_state;
813 WSAStartup(MAKEWORD(2, 2), &wsa_state);
816 // Setup up everything
817 // TODO: we should not open listening sockets yet
819 if(!setup_network(mesh)) {
820 meshlink_close(mesh);
821 meshlink_errno = MESHLINK_ENETWORK;
828 static void *meshlink_main_loop(void *arg) {
829 meshlink_handle_t *mesh = arg;
831 try_outgoing_connections(mesh);
838 bool meshlink_start(meshlink_handle_t *mesh) {
840 meshlink_errno = MESHLINK_EINVAL;
844 // TODO: open listening sockets first
846 //Check that a valid name is set
848 fprintf(stderr, "No name given!\n");
849 meshlink_errno = MESHLINK_EINVAL;
853 // Start the main thread
855 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
856 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
857 memset(&mesh->thread, 0, sizeof mesh->thread);
858 meshlink_errno = MESHLINK_EINTERNAL;
862 mesh->threadstarted=true;
865 if(!discovery_start(mesh))
871 void meshlink_stop(meshlink_handle_t *mesh) {
873 meshlink_errno = MESHLINK_EINVAL;
878 discovery_stop(mesh);
880 // Shut down the listening sockets to signal the main thread to shut down
882 for(int i = 0; i < mesh->listen_sockets; i++) {
883 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
884 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
887 // Wait for the main thread to finish
889 pthread_join(mesh->thread, NULL);
892 void meshlink_close(meshlink_handle_t *mesh) {
893 if(!mesh || !mesh->confbase) {
894 meshlink_errno = MESHLINK_EINVAL;
898 // Close and free all resources used.
900 close_network_connections(mesh);
902 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
904 exit_configuration(&mesh->config);
905 event_loop_exit(&mesh->loop);
912 ecdsa_free(mesh->invitation_key);
915 free(mesh->confbase);
917 memset(mesh, 0, sizeof *mesh);
922 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
924 meshlink_errno = MESHLINK_EINVAL;
928 mesh->receive_cb = cb;
931 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
933 meshlink_errno = MESHLINK_EINVAL;
937 mesh->node_status_cb = cb;
940 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
942 meshlink_errno = MESHLINK_EINVAL;
947 mesh->log_level = level;
950 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
951 if(!mesh || !destination) {
952 meshlink_errno = MESHLINK_EINVAL;
960 meshlink_errno = MESHLINK_EINVAL;
964 /* If there is no outgoing list yet, create one. */
966 if(!mesh->outpacketqueue)
967 mesh->outpacketqueue = list_alloc(NULL);
969 //add packet to the queue
970 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
971 packet_in_queue->destination=destination;
972 packet_in_queue->data=data;
973 packet_in_queue->len=len;
974 pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
975 list_insert_head(mesh->outpacketqueue,packet_in_queue);
976 pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
979 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
983 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
985 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
987 outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
989 list_delete_tail(mesh->outpacketqueue);
992 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
997 packet.probe = false;
998 memset(hdr, 0, sizeof *hdr);
999 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
1000 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
1002 packet.len = sizeof *hdr + p->len;
1003 memcpy(packet.data + sizeof *hdr, p->data, p->len);
1005 mesh->self->in_packets++;
1006 mesh->self->in_bytes += packet.len;
1007 route(mesh, mesh->self, &packet);
1011 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1012 if(!mesh || !destination) {
1013 meshlink_errno = MESHLINK_EINVAL;
1017 node_t *n = (node_t *)destination;
1018 if(!n->status.reachable)
1020 else if(n->mtuprobes > 30 && n->minmtu)
1026 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1027 if(!mesh || !node) {
1028 meshlink_errno = MESHLINK_EINVAL;
1032 node_t *n = (node_t *)node;
1034 if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1035 meshlink_errno = MESHLINK_EINTERNAL;
1039 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1042 meshlink_errno = MESHLINK_EINTERNAL;
1047 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1048 if(!mesh || !name) {
1049 meshlink_errno = MESHLINK_EINVAL;
1053 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1056 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1057 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1058 meshlink_errno = MESHLINK_EINVAL;
1062 meshlink_node_t **result;
1065 pthread_mutex_lock(&(mesh->nodes_mutex));
1067 *nmemb = mesh->nodes->count;
1068 result = realloc(nodes, *nmemb * sizeof *nodes);
1071 meshlink_node_t **p = result;
1072 for splay_each(node_t, n, mesh->nodes)
1073 *p++ = (meshlink_node_t *)n;
1077 meshlink_errno = MESHLINK_ENOMEM;
1080 pthread_mutex_unlock(&(mesh->nodes_mutex));
1085 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1086 if(!mesh || !data || !len || !signature || !siglen) {
1087 meshlink_errno = MESHLINK_EINVAL;
1091 if(*siglen < MESHLINK_SIGLEN) {
1092 meshlink_errno = MESHLINK_EINVAL;
1096 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1097 meshlink_errno = MESHLINK_EINTERNAL;
1101 *siglen = MESHLINK_SIGLEN;
1105 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1106 if(!mesh || !data || !len || !signature) {
1107 meshlink_errno = MESHLINK_EINVAL;
1111 if(siglen != MESHLINK_SIGLEN) {
1112 meshlink_errno = MESHLINK_EINVAL;
1116 struct node_t *n = (struct node_t *)source;
1117 node_read_ecdsa_public_key(mesh, n);
1119 meshlink_errno = MESHLINK_EINTERNAL;
1123 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1126 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1127 char filename[PATH_MAX];
1129 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1130 if(mkdir(filename, 0700) && errno != EEXIST) {
1131 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1132 meshlink_errno = MESHLINK_ESTORAGE;
1136 // Count the number of valid invitations, clean up old ones
1137 DIR *dir = opendir(filename);
1139 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1140 meshlink_errno = MESHLINK_ESTORAGE;
1147 time_t deadline = time(NULL) - 604800; // 1 week in the past
1149 while((ent = readdir(dir))) {
1150 if(strlen(ent->d_name) != 24)
1152 char invname[PATH_MAX];
1154 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1155 if(!stat(invname, &st)) {
1156 if(mesh->invitation_key && deadline < st.st_mtime)
1161 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1167 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1169 meshlink_errno = MESHLINK_ESTORAGE;
1175 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1177 // Remove the key if there are no outstanding invitations.
1180 if(mesh->invitation_key) {
1181 ecdsa_free(mesh->invitation_key);
1182 mesh->invitation_key = NULL;
1186 if(mesh->invitation_key)
1189 // Create a new key if necessary.
1190 FILE *f = fopen(filename, "r");
1192 if(errno != ENOENT) {
1193 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1194 meshlink_errno = MESHLINK_ESTORAGE;
1198 mesh->invitation_key = ecdsa_generate();
1199 if(!mesh->invitation_key) {
1200 fprintf(stderr, "Could not generate a new key!\n");
1201 meshlink_errno = MESHLINK_EINTERNAL;
1204 f = fopen(filename, "w");
1206 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1207 meshlink_errno = MESHLINK_ESTORAGE;
1210 chmod(filename, 0600);
1211 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1214 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1216 if(!mesh->invitation_key) {
1217 fprintf(stderr, "Could not read private key from %s\n", filename);
1218 meshlink_errno = MESHLINK_ESTORAGE;
1222 return mesh->invitation_key;
1225 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1226 if(!mesh || !address) {
1227 meshlink_errno = MESHLINK_EINVAL;
1231 for(const char *p = address; *p; p++) {
1232 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1234 fprintf(stderr, "Invalid character in address: %s\n", address);
1235 meshlink_errno = MESHLINK_EINVAL;
1239 return append_config_file(mesh, mesh->self->name, "Address", address);
1242 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1244 meshlink_errno = MESHLINK_EINVAL;
1248 // Check validity of the new node's name
1249 if(!check_id(name)) {
1250 fprintf(stderr, "Invalid name for node.\n");
1251 meshlink_errno = MESHLINK_EINVAL;
1255 // Ensure no host configuration file with that name exists
1256 char filename[PATH_MAX];
1257 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1258 if(!access(filename, F_OK)) {
1259 fprintf(stderr, "A host config file for %s already exists!\n", name);
1260 meshlink_errno = MESHLINK_EEXIST;
1264 // Ensure no other nodes know about this name
1265 if(meshlink_get_node(mesh, name)) {
1266 fprintf(stderr, "A node with name %s is already known!\n", name);
1267 meshlink_errno = MESHLINK_EEXIST;
1271 // Get the local address
1272 char *address = get_my_hostname(mesh);
1274 fprintf(stderr, "No Address known for ourselves!\n");
1275 meshlink_errno = MESHLINK_ERESOLV;
1279 if(!refresh_invitation_key(mesh)) {
1280 meshlink_errno = MESHLINK_EINTERNAL;
1286 // Create a hash of the key.
1287 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1288 sha512(fingerprint, strlen(fingerprint), hash);
1289 b64encode_urlsafe(hash, hash, 18);
1291 // Create a random cookie for this invitation.
1293 randomize(cookie, 18);
1295 // Create a filename that doesn't reveal the cookie itself
1296 char buf[18 + strlen(fingerprint)];
1297 char cookiehash[64];
1298 memcpy(buf, cookie, 18);
1299 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1300 sha512(buf, sizeof buf, cookiehash);
1301 b64encode_urlsafe(cookiehash, cookiehash, 18);
1303 b64encode_urlsafe(cookie, cookie, 18);
1307 // Create a file containing the details of the invitation.
1308 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1309 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1311 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1312 meshlink_errno = MESHLINK_ESTORAGE;
1315 FILE *f = fdopen(ifd, "w");
1319 // Fill in the details.
1320 fprintf(f, "Name = %s\n", name);
1322 // fprintf(f, "NetName = %s\n", netname);
1323 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1325 // Copy Broadcast and Mode
1326 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1327 FILE *tc = fopen(filename, "r");
1330 while(fgets(buf, sizeof buf, tc)) {
1331 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1332 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1334 // Make sure there is a newline character.
1335 if(!strchr(buf, '\n'))
1341 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1342 meshlink_errno = MESHLINK_ESTORAGE;
1346 fprintf(f, "#---------------------------------------------------------------#\n");
1347 fprintf(f, "Name = %s\n", mesh->self->name);
1349 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1353 // Create an URL from the local address, key hash and cookie
1355 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1361 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1362 if(!mesh || !invitation) {
1363 meshlink_errno = MESHLINK_EINVAL;
1367 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1368 char copy[strlen(invitation) + 1];
1369 strcpy(copy, invitation);
1371 // Split the invitation URL into hostname, port, key hash and cookie.
1373 char *slash = strchr(copy, '/');
1379 if(strlen(slash) != 48)
1382 char *address = copy;
1384 if(*address == '[') {
1386 char *bracket = strchr(address, ']');
1390 if(bracket[1] == ':')
1393 port = strchr(address, ':');
1401 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1404 // Generate a throw-away key for the invitation.
1405 ecdsa_t *key = ecdsa_generate();
1407 meshlink_errno = MESHLINK_EINTERNAL;
1411 char *b64key = ecdsa_get_base64_public_key(key);
1413 //Before doing meshlink_join make sure we are not connected to another mesh
1414 if ( mesh->threadstarted ){
1418 // Connect to the meshlink daemon mentioned in the URL.
1419 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1421 meshlink_errno = MESHLINK_ERESOLV;
1425 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1426 if(mesh->sock <= 0) {
1427 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1429 meshlink_errno = MESHLINK_ENETWORK;
1433 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1434 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1435 closesocket(mesh->sock);
1437 meshlink_errno = MESHLINK_ENETWORK;
1443 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1445 // Tell him we have an invitation, and give him our throw-away key.
1449 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1450 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1451 closesocket(mesh->sock);
1452 meshlink_errno = MESHLINK_ENETWORK;
1458 char hisname[4096] = "";
1459 int code, hismajor, hisminor = 0;
1461 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) {
1462 fprintf(stderr, "Cannot read greeting from peer\n");
1463 closesocket(mesh->sock);
1464 meshlink_errno = MESHLINK_ENETWORK;
1468 // Check if the hash of the key he gave us matches the hash in the URL.
1469 char *fingerprint = mesh->line + 2;
1471 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1472 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1473 meshlink_errno = MESHLINK_EINTERNAL;
1476 if(memcmp(hishash, mesh->hash, 18)) {
1477 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1478 meshlink_errno = MESHLINK_EPEER;
1483 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1485 meshlink_errno = MESHLINK_EINTERNAL;
1489 // Start an SPTPS session
1490 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1491 meshlink_errno = MESHLINK_EINTERNAL;
1495 // Feed rest of input buffer to SPTPS
1496 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1497 meshlink_errno = MESHLINK_EPEER;
1503 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1507 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1508 meshlink_errno = MESHLINK_ENETWORK;
1512 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1513 meshlink_errno = MESHLINK_EPEER;
1518 sptps_stop(&mesh->sptps);
1521 closesocket(mesh->sock);
1523 if(!mesh->success) {
1524 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1525 meshlink_errno = MESHLINK_EPEER;
1532 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1533 meshlink_errno = MESHLINK_EINVAL;
1537 char *meshlink_export(meshlink_handle_t *mesh) {
1539 meshlink_errno = MESHLINK_EINVAL;
1543 char filename[PATH_MAX];
1544 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1545 FILE *f = fopen(filename, "r");
1547 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1548 meshlink_errno = MESHLINK_ESTORAGE;
1552 fseek(f, 0, SEEK_END);
1553 int fsize = ftell(f);
1556 size_t len = fsize + 9 + strlen(mesh->self->name);
1557 char *buf = xmalloc(len);
1558 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1559 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1560 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1562 meshlink_errno = MESHLINK_ESTORAGE;
1571 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1572 if(!mesh || !data) {
1573 meshlink_errno = MESHLINK_EINVAL;
1577 if(strncmp(data, "Name = ", 7)) {
1578 fprintf(stderr, "Invalid data\n");
1579 meshlink_errno = MESHLINK_EPEER;
1583 char *end = strchr(data + 7, '\n');
1585 fprintf(stderr, "Invalid data\n");
1586 meshlink_errno = MESHLINK_EPEER;
1590 int len = end - (data + 7);
1592 memcpy(name, data + 7, len);
1594 if(!check_id(name)) {
1595 fprintf(stderr, "Invalid Name\n");
1596 meshlink_errno = MESHLINK_EPEER;
1600 char filename[PATH_MAX];
1601 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1602 if(!access(filename, F_OK)) {
1603 fprintf(stderr, "File %s already exists, not importing\n", filename);
1604 meshlink_errno = MESHLINK_EEXIST;
1608 if(errno != ENOENT) {
1609 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1610 meshlink_errno = MESHLINK_ESTORAGE;
1614 FILE *f = fopen(filename, "w");
1616 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1617 meshlink_errno = MESHLINK_ESTORAGE;
1621 fwrite(end + 1, strlen(end + 1), 1, f);
1624 load_all_nodes(mesh);
1629 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1630 if(!mesh || !node) {
1631 meshlink_errno = MESHLINK_EINVAL;
1637 n->status.blacklisted=true;
1638 fprintf(stderr, "Blacklisted %s.\n",node->name);
1640 //Make blacklisting persistent in the config file
1641 append_config_file(mesh, n->name, "blacklisted", "yes");
1646 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1647 if(!mesh || !node) {
1648 meshlink_errno = MESHLINK_EINVAL;
1652 node_t *n = (node_t *)node;
1653 n->status.blacklisted = false;
1655 //TODO: remove blacklisted = yes from the config file
1660 /* Hint that a hostname may be found at an address
1661 * See header file for detailed comment.
1663 extern void meshlink_hint_address(meshlink_handle_t *mesh, char *hostname, struct sockaddr *addr) {
1664 if(!mesh || !hostname || !addr)
1668 char *addr_str = malloc(MAX_ADDRESS_LENGTH*sizeof(char));
1669 memset(addr_str, 0, MAX_ADDRESS_LENGTH*sizeof(char));
1671 char *port_str = malloc(MAX_PORT_LENGTH*sizeof(char));
1672 memset(port_str, 0, MAX_PORT_LENGTH*sizeof(char));
1674 // extra byte for a space, and one to make sure string is null-terminated
1675 int full_addr_len = MAX_ADDRESS_LENGTH + MAX_PORT_LENGTH + 2;
1677 char *full_addr_str = malloc(full_addr_len*sizeof(char));
1678 memset(full_addr_str, 0, full_addr_len*sizeof(char));
1680 // check that hostname matches an existing node
1681 n = lookup_node(mesh, hostname);
1685 // get address and port number
1686 if(!get_ip_str(addr, addr_str, MAX_ADDRESS_LENGTH))
1688 if(!get_port_str(addr, port_str, MAX_ADDRESS_LENGTH))
1691 // append_config_file expects an address, a space, and then a port number
1692 strcat(full_addr_str, addr_str);
1693 strcat(full_addr_str, " ");
1694 strcat(full_addr_str, port_str);
1696 append_config_file(mesh, n->name, "Address", full_addr_str);
1700 free(full_addr_str);
1702 // TODO do we want to fire off a connection attempt right away?
1705 static void __attribute__((constructor)) meshlink_init(void) {
1709 static void __attribute__((destructor)) meshlink_exit(void) {