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 */
34 #include "meshlink_internal.h"
41 #include "ed25519/sha512.h"
42 #include "discovery.h"
45 #define MSG_NOSIGNAL 0
48 __thread meshlink_errno_t meshlink_errno;
50 //TODO: this can go away completely
51 const var_t variables[] = {
52 /* Server configuration */
53 {"AddressFamily", VAR_SERVER},
54 {"AutoConnect", VAR_SERVER | VAR_SAFE},
55 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
56 {"BindToInterface", VAR_SERVER},
57 {"Broadcast", VAR_SERVER | VAR_SAFE},
58 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
59 {"DecrementTTL", VAR_SERVER},
60 {"Device", VAR_SERVER},
61 {"DeviceType", VAR_SERVER},
62 {"DirectOnly", VAR_SERVER},
63 {"ECDSAPrivateKeyFile", VAR_SERVER},
64 {"ExperimentalProtocol", VAR_SERVER},
65 {"Forwarding", VAR_SERVER},
66 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
67 {"Hostnames", VAR_SERVER},
68 {"IffOneQueue", VAR_SERVER},
69 {"Interface", VAR_SERVER},
70 {"KeyExpire", VAR_SERVER},
71 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
72 {"LocalDiscovery", VAR_SERVER},
73 {"MACExpire", VAR_SERVER},
74 {"MaxConnectionBurst", VAR_SERVER},
75 {"MaxOutputBufferSize", VAR_SERVER},
76 {"MaxTimeout", VAR_SERVER},
77 {"Mode", VAR_SERVER | VAR_SAFE},
79 {"PingInterval", VAR_SERVER},
80 {"PingTimeout", VAR_SERVER},
81 {"PriorityInheritance", VAR_SERVER},
82 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
83 {"PrivateKeyFile", VAR_SERVER},
84 {"ProcessPriority", VAR_SERVER},
85 {"Proxy", VAR_SERVER},
86 {"ReplayWindow", VAR_SERVER},
87 {"ScriptsExtension", VAR_SERVER},
88 {"ScriptsInterpreter", VAR_SERVER},
89 {"StrictSubnets", VAR_SERVER},
90 {"TunnelServer", VAR_SERVER},
91 {"VDEGroup", VAR_SERVER},
92 {"VDEPort", VAR_SERVER},
93 /* Host configuration */
94 {"Address", VAR_HOST | VAR_MULTIPLE},
95 {"Cipher", VAR_SERVER | VAR_HOST},
96 {"ClampMSS", VAR_SERVER | VAR_HOST},
97 {"Compression", VAR_SERVER | VAR_HOST},
98 {"Digest", VAR_SERVER | VAR_HOST},
99 {"ECDSAPublicKey", VAR_HOST},
100 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
101 {"IndirectData", VAR_SERVER | VAR_HOST},
102 {"MACLength", VAR_SERVER | VAR_HOST},
103 {"PMTU", VAR_SERVER | VAR_HOST},
104 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
106 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
107 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
108 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
109 {"TCPOnly", VAR_SERVER | VAR_HOST},
110 {"Weight", VAR_HOST | VAR_SAFE},
114 static bool fcopy(FILE *out, const char *filename) {
115 FILE *in = fopen(filename, "r");
117 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
123 while((len = fread(buf, 1, sizeof buf, in)))
124 fwrite(buf, len, 1, out);
129 static int rstrip(char *value) {
130 int len = strlen(value);
131 while(len && strchr("\t\r\n ", value[len - 1]))
136 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
138 if(!filename || (*hostname && *port))
141 FILE *f = fopen(filename, "r");
145 while(fgets(line, sizeof line, f)) {
149 p += strcspn(p, "\t =");
152 q = p + strspn(p, "\t ");
154 q += 1 + strspn(q + 1, "\t ");
156 p = q + strcspn(q, "\t ");
159 p += strspn(p, "\t ");
160 p[strcspn(p, "\t ")] = 0;
162 if(!*port && !strcasecmp(line, "Port")) {
164 } else if(!*hostname && !strcasecmp(line, "Address")) {
165 *hostname = xstrdup(q);
172 if(*hostname && *port)
178 static char *get_my_hostname(meshlink_handle_t* mesh) {
179 char *hostname = NULL;
181 char *hostport = NULL;
182 char *name = mesh->self->name;
183 char filename[PATH_MAX] = "";
187 // Use first Address statement in own host config file
188 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
189 scan_for_hostname(filename, &hostname, &port);
194 // If that doesn't work, guess externally visible hostname
195 fprintf(stderr, "Trying to discover externally visible hostname...\n");
196 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
197 struct addrinfo *aip = ai;
198 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
201 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
203 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
209 send(s, request, sizeof request - 1, 0);
210 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
213 if(line[len - 1] == '\n')
215 char *p = strrchr(line, '\n');
217 hostname = xstrdup(p + 1);
230 // Check that the hostname is reasonable
232 for(char *p = hostname; *p; p++) {
233 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
235 // If not, forget it.
245 f = fopen(filename, "a");
247 fprintf(f, "\nAddress = %s\n", hostname);
250 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
255 if(strchr(hostname, ':'))
256 xasprintf(&hostport, "[%s]:%s", hostname, port);
258 xasprintf(&hostport, "%s:%s", hostname, port);
260 if(strchr(hostname, ':'))
261 xasprintf(&hostport, "[%s]", hostname);
263 hostport = xstrdup(hostname);
271 static char *get_line(const char **data) {
280 static char line[1024];
281 const char *end = strchr(*data, '\n');
282 size_t len = end ? end - *data : strlen(*data);
283 if(len >= sizeof line) {
284 fprintf(stderr, "Maximum line length exceeded!\n");
287 if(len && !isprint(**data))
290 memcpy(line, *data, len);
301 static char *get_value(const char *data, const char *var) {
302 char *line = get_line(&data);
306 char *sep = line + strcspn(line, " \t=");
307 char *val = sep + strspn(sep, " \t");
309 val += 1 + strspn(val + 1, " \t");
311 if(strcasecmp(line, var))
316 static bool try_bind(int port) {
317 struct addrinfo *ai = NULL;
318 struct addrinfo hint = {
319 .ai_flags = AI_PASSIVE,
320 .ai_family = AF_UNSPEC,
321 .ai_socktype = SOCK_STREAM,
322 .ai_protocol = IPPROTO_TCP,
326 snprintf(portstr, sizeof portstr, "%d", port);
328 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
332 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
337 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
350 static int check_port(meshlink_handle_t *mesh) {
354 fprintf(stderr, "Warning: could not bind to port 655.\n");
356 for(int i = 0; i < 100; 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);
369 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
374 fprintf(stderr, "Please change MeshLink's Port manually.\n");
378 static bool finalize_join(meshlink_handle_t *mesh) {
379 char *name = xstrdup(get_value(mesh->data, "Name"));
381 fprintf(stderr, "No Name found in invitation!\n");
385 if(!check_id(name)) {
386 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
390 char filename[PATH_MAX];
391 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
393 FILE *f = fopen(filename, "w");
395 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
399 fprintf(f, "Name = %s\n", name);
401 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
402 FILE *fh = fopen(filename, "w");
404 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
409 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
410 // Other chunks go unfiltered to their respective host config files
411 const char *p = mesh->data;
414 while((l = get_line(&p))) {
419 // Split line into variable and value
420 int len = strcspn(l, "\t =");
422 value += strspn(value, "\t ");
425 value += strspn(value, "\t ");
430 if(!strcasecmp(l, "Name"))
431 if(strcmp(value, name))
435 else if(!strcasecmp(l, "NetName"))
438 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
441 for(i = 0; variables[i].name; i++) {
442 if(strcasecmp(l, variables[i].name))
448 // Ignore unknown and unsafe variables
450 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
452 } else if(!(variables[i].type & VAR_SAFE)) {
453 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
457 // Copy the safe variable to the right config file
458 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
463 while(l && !strcasecmp(l, "Name")) {
464 if(!check_id(value)) {
465 fprintf(stderr, "Invalid Name found in invitation.\n");
469 if(!strcmp(value, name)) {
470 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
474 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
475 f = fopen(filename, "w");
478 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
482 while((l = get_line(&p))) {
483 if(!strcmp(l, "#---------------------------------------------------------------#"))
485 int len = strcspn(l, "\t =");
486 if(len == 4 && !strncasecmp(l, "Name", 4)) {
488 value += strspn(value, "\t ");
491 value += strspn(value, "\t ");
504 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
508 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
509 fprintf(fh, "Port = %s\n", mesh->myport);
513 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
516 free(mesh->self->name);
517 free(mesh->self->connection->name);
518 mesh->self->name = xstrdup(name);
519 mesh->self->connection->name = name;
521 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
523 load_all_nodes(mesh);
528 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
529 meshlink_handle_t* mesh = handle;
531 int result = send(mesh->sock, data, len, 0);
532 if(result == -1 && errno == EINTR)
542 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
543 meshlink_handle_t* mesh = handle;
545 case SPTPS_HANDSHAKE:
546 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
549 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
550 memcpy(mesh->data + mesh->thedatalen, msg, len);
551 mesh->thedatalen += len;
552 mesh->data[mesh->thedatalen] = 0;
556 return finalize_join(mesh);
559 fprintf(stderr, "Invitation succesfully accepted.\n");
560 shutdown(mesh->sock, SHUT_RDWR);
561 mesh->success = true;
571 static bool recvline(meshlink_handle_t* mesh, size_t len) {
572 char *newline = NULL;
577 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
578 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
579 if(result == -1 && errno == EINTR)
583 mesh->blen += result;
586 if(newline - mesh->buffer >= len)
589 len = newline - mesh->buffer;
591 memcpy(mesh->line, mesh->buffer, len);
593 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
594 mesh->blen -= len + 1;
598 static bool sendline(int fd, char *format, ...) {
599 static char buffer[4096];
604 va_start(ap, format);
605 blen = vsnprintf(buffer, sizeof buffer, format, ap);
608 if(blen < 1 || blen >= sizeof buffer)
615 int result = send(fd, p, blen, MSG_NOSIGNAL);
616 if(result == -1 && errno == EINTR)
627 static const char *errstr[] = {
628 [MESHLINK_OK] = "No error",
629 [MESHLINK_ENOMEM] = "Out of memory",
630 [MESHLINK_ENOENT] = "No such node",
633 const char *meshlink_strerror(meshlink_errno_t err) {
634 if(err < 0 || err >= sizeof errstr / sizeof *errstr)
635 return "Invalid error code";
639 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
642 char pubname[PATH_MAX], privname[PATH_MAX];
644 fprintf(stderr, "Generating ECDSA keypair:\n");
646 if(!(key = ecdsa_generate())) {
647 fprintf(stderr, "Error during key generation!\n");
650 fprintf(stderr, "Done.\n");
652 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
653 f = fopen(privname, "w");
659 fchmod(fileno(f), 0600);
662 if(!ecdsa_write_pem_private_key(key, f)) {
663 fprintf(stderr, "Error writing private key!\n");
672 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
673 f = fopen(pubname, "a");
678 char *pubkey = ecdsa_get_base64_public_key(key);
679 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
688 static bool meshlink_setup(meshlink_handle_t *mesh) {
689 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
690 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
694 char filename[PATH_MAX];
695 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
697 if(mkdir(filename, 0777) && errno != EEXIST) {
698 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
702 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
704 if(!access(filename, F_OK)) {
705 fprintf(stderr, "Configuration file %s already exists!\n", filename);
709 FILE *f = fopen(filename, "w");
711 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
715 fprintf(f, "Name = %s\n", mesh->name);
718 if(!ecdsa_keygen(mesh))
726 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
727 // Validate arguments provided by the application
728 bool usingname = false;
730 if(!confbase || !*confbase) {
731 fprintf(stderr, "No confbase given!\n");
735 if(!name || !*name) {
736 fprintf(stderr, "No name given!\n");
739 else { //check name only if there is a name != NULL
741 if(!check_id(name)) {
742 fprintf(stderr, "Invalid name given!\n");
744 } else { usingname = true;}
747 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
748 mesh->confbase = xstrdup(confbase);
749 if (usingname) mesh->name = xstrdup(name);
750 pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
751 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
752 mesh->threadstarted = false;
753 event_loop_init(&mesh->loop);
754 mesh->loop.data = mesh;
756 // TODO: should be set by a function.
757 mesh->debug_level = 5;
759 // Check whether meshlink.conf already exists
761 char filename[PATH_MAX];
762 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
764 if(access(filename, R_OK)) {
765 if(errno == ENOENT) {
767 meshlink_setup(mesh);
769 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
770 return meshlink_close(mesh), NULL;
774 // Read the configuration
776 init_configuration(&mesh->config);
778 if(!read_server_config(mesh))
779 return meshlink_close(mesh), NULL;
782 struct WSAData wsa_state;
783 WSAStartup(MAKEWORD(2, 2), &wsa_state);
786 // Setup up everything
787 // TODO: we should not open listening sockets yet
789 if(!setup_network(mesh))
790 return meshlink_close(mesh), NULL;
795 static void *meshlink_main_loop(void *arg) {
796 meshlink_handle_t *mesh = arg;
798 try_outgoing_connections(mesh);
805 bool meshlink_start(meshlink_handle_t *mesh) {
809 // TODO: open listening sockets first
811 //Check that a valid name is set
813 fprintf(stderr, "No name given!\n");
817 // Start the main thread
819 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
820 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
821 memset(&mesh->thread, 0, sizeof mesh->thread);
825 mesh->threadstarted=true;
828 if(!discovery_start(mesh))
834 void meshlink_stop(meshlink_handle_t *mesh) {
839 discovery_stop(mesh);
841 // Shut down the listening sockets to signal the main thread to shut down
843 for(int i = 0; i < mesh->listen_sockets; i++) {
844 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
845 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
848 // Wait for the main thread to finish
850 pthread_join(mesh->thread, NULL);
853 void meshlink_close(meshlink_handle_t *mesh) {
854 if(!mesh || !mesh->confbase)
857 // Close and free all resources used.
859 close_network_connections(mesh);
861 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
863 exit_configuration(&mesh->config);
864 event_loop_exit(&mesh->loop);
871 ecdsa_free(mesh->invitation_key);
874 free(mesh->confbase);
876 memset(mesh, 0, sizeof *mesh);
881 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
884 mesh->receive_cb = cb;
887 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
890 mesh->node_status_cb = cb;
893 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
897 mesh->log_level = level;
900 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
901 if(!mesh || !destination)
908 /* If there is no outgoing list yet, create one. */
910 if(!mesh->outpacketqueue)
911 mesh->outpacketqueue = list_alloc(NULL);
913 //add packet to the queue
914 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
915 packet_in_queue->destination=destination;
916 packet_in_queue->data=data;
917 packet_in_queue->len=len;
918 pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
919 list_insert_head(mesh->outpacketqueue,packet_in_queue);
920 pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
923 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
927 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
929 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
931 outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
933 list_delete_tail(mesh->outpacketqueue);
936 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
941 packet.probe = false;
942 memset(hdr, 0, sizeof *hdr);
943 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
944 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
946 packet.len = sizeof *hdr + p->len;
947 memcpy(packet.data + sizeof *hdr, p->data, p->len);
949 mesh->self->in_packets++;
950 mesh->self->in_bytes += packet.len;
951 route(mesh, mesh->self, &packet);
955 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
956 if(!mesh || !destination)
959 node_t *n = (node_t *)destination;
960 if(!n->status.reachable)
962 else if(n->mtuprobes > 30 && n->minmtu)
968 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
971 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
974 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
975 if(!mesh || (nmemb && !nodes))
978 meshlink_node_t **result, **p;
981 pthread_mutex_lock(&(mesh->nodes_mutex));
983 *nmemb = mesh->nodes->count;
984 result = realloc(nodes, *nmemb * sizeof *nodes);
987 for splay_each(node_t, n, mesh->nodes)
988 *p++ = (meshlink_node_t *)n;
992 meshlink_errno = MESHLINK_ENOMEM;
995 pthread_mutex_unlock(&(mesh->nodes_mutex));
1000 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1001 if(!mesh || !data || !len || !signature || !siglen)
1003 if(*siglen < MESHLINK_SIGLEN)
1005 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature))
1007 *siglen = MESHLINK_SIGLEN;
1011 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1012 if(!mesh || !data || !len || !signature)
1014 if(siglen != MESHLINK_SIGLEN)
1016 struct node_t *n = (struct node_t *)source;
1017 node_read_ecdsa_public_key(mesh, n);
1020 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1023 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1024 char filename[PATH_MAX];
1026 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1027 if(mkdir(filename, 0700) && errno != EEXIST) {
1028 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1032 // Count the number of valid invitations, clean up old ones
1033 DIR *dir = opendir(filename);
1035 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1042 time_t deadline = time(NULL) - 604800; // 1 week in the past
1044 while((ent = readdir(dir))) {
1045 if(strlen(ent->d_name) != 24)
1047 char invname[PATH_MAX];
1049 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1050 if(!stat(invname, &st)) {
1051 if(mesh->invitation_key && deadline < st.st_mtime)
1056 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1062 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1069 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1071 // Remove the key if there are no outstanding invitations.
1074 if(mesh->invitation_key) {
1075 ecdsa_free(mesh->invitation_key);
1076 mesh->invitation_key = NULL;
1080 if(mesh->invitation_key)
1083 // Create a new key if necessary.
1084 FILE *f = fopen(filename, "r");
1086 if(errno != ENOENT) {
1087 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1091 mesh->invitation_key = ecdsa_generate();
1092 if(!mesh->invitation_key) {
1093 fprintf(stderr, "Could not generate a new key!\n");
1096 f = fopen(filename, "w");
1098 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1101 chmod(filename, 0600);
1102 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1105 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1107 if(!mesh->invitation_key)
1108 fprintf(stderr, "Could not read private key from %s\n", filename);
1111 return mesh->invitation_key;
1114 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1115 if(!mesh || !address)
1118 for(const char *p = address; *p; p++) {
1119 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1121 fprintf(stderr, "Invalid character in address: %s\n", address);
1125 return append_config_file(mesh, mesh->self->name, "Address", address);
1128 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1132 // Check validity of the new node's name
1133 if(!check_id(name)) {
1134 fprintf(stderr, "Invalid name for node.\n");
1138 // Ensure no host configuration file with that name exists
1139 char filename[PATH_MAX];
1140 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1141 if(!access(filename, F_OK)) {
1142 fprintf(stderr, "A host config file for %s already exists!\n", name);
1146 // Ensure no other nodes know about this name
1147 if(meshlink_get_node(mesh, name)) {
1148 fprintf(stderr, "A node with name %s is already known!\n", name);
1152 // Get the local address
1153 char *address = get_my_hostname(mesh);
1155 fprintf(stderr, "No Address known for ourselves!\n");
1159 if(!refresh_invitation_key(mesh))
1164 // Create a hash of the key.
1165 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1166 sha512(fingerprint, strlen(fingerprint), hash);
1167 b64encode_urlsafe(hash, hash, 18);
1169 // Create a random cookie for this invitation.
1171 randomize(cookie, 18);
1173 // Create a filename that doesn't reveal the cookie itself
1174 char buf[18 + strlen(fingerprint)];
1175 char cookiehash[64];
1176 memcpy(buf, cookie, 18);
1177 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1178 sha512(buf, sizeof buf, cookiehash);
1179 b64encode_urlsafe(cookiehash, cookiehash, 18);
1181 b64encode_urlsafe(cookie, cookie, 18);
1185 // Create a file containing the details of the invitation.
1186 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1187 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1189 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1192 FILE *f = fdopen(ifd, "w");
1196 // Fill in the details.
1197 fprintf(f, "Name = %s\n", name);
1199 // fprintf(f, "NetName = %s\n", netname);
1200 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1202 // Copy Broadcast and Mode
1203 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1204 FILE *tc = fopen(filename, "r");
1207 while(fgets(buf, sizeof buf, tc)) {
1208 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1209 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1211 // Make sure there is a newline character.
1212 if(!strchr(buf, '\n'))
1218 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1222 fprintf(f, "#---------------------------------------------------------------#\n");
1223 fprintf(f, "Name = %s\n", mesh->self->name);
1225 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1229 // Create an URL from the local address, key hash and cookie
1231 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1237 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1238 if(!mesh || !invitation)
1241 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1242 char copy[strlen(invitation) + 1];
1243 strcpy(copy, invitation);
1245 // Split the invitation URL into hostname, port, key hash and cookie.
1247 char *slash = strchr(copy, '/');
1253 if(strlen(slash) != 48)
1256 char *address = copy;
1258 if(*address == '[') {
1260 char *bracket = strchr(address, ']');
1264 if(bracket[1] == ':')
1267 port = strchr(address, ':');
1275 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1278 // Generate a throw-away key for the invitation.
1279 ecdsa_t *key = ecdsa_generate();
1283 char *b64key = ecdsa_get_base64_public_key(key);
1285 //Before doing meshlink_join make sure we are not connected to another mesh
1286 if ( mesh->threadstarted ){
1290 // Connect to the meshlink daemon mentioned in the URL.
1291 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1295 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1296 if(mesh->sock <= 0) {
1297 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1302 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1303 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1304 closesocket(mesh->sock);
1311 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1313 // Tell him we have an invitation, and give him our throw-away key.
1317 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1318 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1319 closesocket(mesh->sock);
1325 char hisname[4096] = "";
1326 int code, hismajor, hisminor = 0;
1328 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) {
1329 fprintf(stderr, "Cannot read greeting from peer\n");
1330 closesocket(mesh->sock);
1334 // Check if the hash of the key he gave us matches the hash in the URL.
1335 char *fingerprint = mesh->line + 2;
1337 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1338 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1341 if(memcmp(hishash, mesh->hash, 18)) {
1342 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1347 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1351 // Start an SPTPS session
1352 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1355 // Feed rest of input buffer to SPTPS
1356 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1361 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1365 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1369 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1373 sptps_stop(&mesh->sptps);
1376 closesocket(mesh->sock);
1378 if(!mesh->success) {
1379 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1386 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1390 char *meshlink_export(meshlink_handle_t *mesh) {
1394 char filename[PATH_MAX];
1395 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1396 FILE *f = fopen(filename, "r");
1398 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1402 fseek(f, 0, SEEK_END);
1403 int fsize = ftell(f);
1406 size_t len = fsize + 9 + strlen(mesh->self->name);
1407 char *buf = xmalloc(len);
1408 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1409 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1410 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1420 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1424 if(strncmp(data, "Name = ", 7)) {
1425 fprintf(stderr, "Invalid data\n");
1429 char *end = strchr(data + 7, '\n');
1431 fprintf(stderr, "Invalid data\n");
1435 int len = end - (data + 7);
1437 memcpy(name, data + 7, len);
1439 if(!check_id(name)) {
1440 fprintf(stderr, "Invalid Name\n");
1444 char filename[PATH_MAX];
1445 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1446 if(!access(filename, F_OK)) {
1447 fprintf(stderr, "File %s already exists, not importing\n", filename);
1451 if(errno != ENOENT) {
1452 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1456 FILE *f = fopen(filename, "w");
1458 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1462 fwrite(end + 1, strlen(end + 1), 1, f);
1465 load_all_nodes(mesh);
1470 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1476 n->status.blacklisted=true;
1477 fprintf(stderr, "Blacklisted %s.\n",node->name);
1479 //Make blacklisting persistent in the config file
1480 append_config_file(mesh, n->name, "blacklisted", "yes");
1485 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1489 node_t *n = (node_t *)node;
1490 n->status.blacklisted = false;
1492 //TODO: remove blacklisted = yes from the config file
1497 static void __attribute__((constructor)) meshlink_init(void) {
1501 static void __attribute__((destructor)) meshlink_exit(void) {