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"
44 #define MSG_NOSIGNAL 0
47 __thread meshlink_errno_t meshlink_errno;
49 //TODO: this can go away completely
50 const var_t variables[] = {
51 /* Server configuration */
52 {"AddressFamily", VAR_SERVER},
53 {"AutoConnect", VAR_SERVER | VAR_SAFE},
54 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
55 {"BindToInterface", VAR_SERVER},
56 {"Broadcast", VAR_SERVER | VAR_SAFE},
57 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
58 {"DecrementTTL", VAR_SERVER},
59 {"Device", VAR_SERVER},
60 {"DeviceType", VAR_SERVER},
61 {"DirectOnly", VAR_SERVER},
62 {"ECDSAPrivateKeyFile", VAR_SERVER},
63 {"ExperimentalProtocol", VAR_SERVER},
64 {"Forwarding", VAR_SERVER},
65 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
66 {"Hostnames", VAR_SERVER},
67 {"IffOneQueue", VAR_SERVER},
68 {"Interface", VAR_SERVER},
69 {"KeyExpire", VAR_SERVER},
70 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
71 {"LocalDiscovery", VAR_SERVER},
72 {"MACExpire", VAR_SERVER},
73 {"MaxConnectionBurst", VAR_SERVER},
74 {"MaxOutputBufferSize", VAR_SERVER},
75 {"MaxTimeout", VAR_SERVER},
76 {"Mode", VAR_SERVER | VAR_SAFE},
78 {"PingInterval", VAR_SERVER},
79 {"PingTimeout", VAR_SERVER},
80 {"PriorityInheritance", VAR_SERVER},
81 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
82 {"PrivateKeyFile", VAR_SERVER},
83 {"ProcessPriority", VAR_SERVER},
84 {"Proxy", VAR_SERVER},
85 {"ReplayWindow", VAR_SERVER},
86 {"ScriptsExtension", VAR_SERVER},
87 {"ScriptsInterpreter", VAR_SERVER},
88 {"StrictSubnets", VAR_SERVER},
89 {"TunnelServer", VAR_SERVER},
90 {"VDEGroup", VAR_SERVER},
91 {"VDEPort", VAR_SERVER},
92 /* Host configuration */
93 {"Address", VAR_HOST | VAR_MULTIPLE},
94 {"Cipher", VAR_SERVER | VAR_HOST},
95 {"ClampMSS", VAR_SERVER | VAR_HOST},
96 {"Compression", VAR_SERVER | VAR_HOST},
97 {"Digest", VAR_SERVER | VAR_HOST},
98 {"ECDSAPublicKey", VAR_HOST},
99 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
100 {"IndirectData", VAR_SERVER | VAR_HOST},
101 {"MACLength", VAR_SERVER | VAR_HOST},
102 {"PMTU", VAR_SERVER | VAR_HOST},
103 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
105 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
106 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
107 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
108 {"TCPOnly", VAR_SERVER | VAR_HOST},
109 {"Weight", VAR_HOST | VAR_SAFE},
113 static bool fcopy(FILE *out, const char *filename) {
114 FILE *in = fopen(filename, "r");
116 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
122 while((len = fread(buf, 1, sizeof buf, in)))
123 fwrite(buf, len, 1, out);
128 static int rstrip(char *value) {
129 int len = strlen(value);
130 while(len && strchr("\t\r\n ", value[len - 1]))
135 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
137 if(!filename || (*hostname && *port))
140 FILE *f = fopen(filename, "r");
144 while(fgets(line, sizeof line, f)) {
148 p += strcspn(p, "\t =");
151 q = p + strspn(p, "\t ");
153 q += 1 + strspn(q + 1, "\t ");
155 p = q + strcspn(q, "\t ");
158 p += strspn(p, "\t ");
159 p[strcspn(p, "\t ")] = 0;
161 if(!*port && !strcasecmp(line, "Port")) {
163 } else if(!*hostname && !strcasecmp(line, "Address")) {
164 *hostname = xstrdup(q);
171 if(*hostname && *port)
177 static char *get_my_hostname(meshlink_handle_t* mesh) {
178 char *hostname = NULL;
180 char *hostport = NULL;
181 char *name = mesh->self->name;
182 char filename[PATH_MAX] = "";
186 // Use first Address statement in own host config file
187 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
188 scan_for_hostname(filename, &hostname, &port);
193 // If that doesn't work, guess externally visible hostname
194 fprintf(stderr, "Trying to discover externally visible hostname...\n");
195 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
196 struct addrinfo *aip = ai;
197 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
200 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
202 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
208 send(s, request, sizeof request - 1, 0);
209 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
212 if(line[len - 1] == '\n')
214 char *p = strrchr(line, '\n');
216 hostname = xstrdup(p + 1);
229 // Check that the hostname is reasonable
231 for(char *p = hostname; *p; p++) {
232 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
234 // If not, forget it.
244 f = fopen(filename, "a");
246 fprintf(f, "\nAddress = %s\n", hostname);
249 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
254 if(strchr(hostname, ':'))
255 xasprintf(&hostport, "[%s]:%s", hostname, port);
257 xasprintf(&hostport, "%s:%s", hostname, port);
259 if(strchr(hostname, ':'))
260 xasprintf(&hostport, "[%s]", hostname);
262 hostport = xstrdup(hostname);
270 static char *get_line(const char **data) {
279 static char line[1024];
280 const char *end = strchr(*data, '\n');
281 size_t len = end ? end - *data : strlen(*data);
282 if(len >= sizeof line) {
283 fprintf(stderr, "Maximum line length exceeded!\n");
286 if(len && !isprint(**data))
289 memcpy(line, *data, len);
300 static char *get_value(const char *data, const char *var) {
301 char *line = get_line(&data);
305 char *sep = line + strcspn(line, " \t=");
306 char *val = sep + strspn(sep, " \t");
308 val += 1 + strspn(val + 1, " \t");
310 if(strcasecmp(line, var))
315 static bool try_bind(int port) {
316 struct addrinfo *ai = NULL;
317 struct addrinfo hint = {
318 .ai_flags = AI_PASSIVE,
319 .ai_family = AF_UNSPEC,
320 .ai_socktype = SOCK_STREAM,
321 .ai_protocol = IPPROTO_TCP,
325 snprintf(portstr, sizeof portstr, "%d", port);
327 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
331 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
336 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
349 static int check_port(meshlink_handle_t *mesh) {
353 fprintf(stderr, "Warning: could not bind to port 655.\n");
355 for(int i = 0; i < 100; i++) {
356 int port = 0x1000 + (rand() & 0x7fff);
358 char filename[PATH_MAX];
359 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
360 FILE *f = fopen(filename, "a");
362 fprintf(stderr, "Please change MeshLink's Port manually.\n");
366 fprintf(f, "Port = %d\n", port);
368 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
373 fprintf(stderr, "Please change MeshLink's Port manually.\n");
377 static bool finalize_join(meshlink_handle_t *mesh) {
378 char *name = xstrdup(get_value(mesh->data, "Name"));
380 fprintf(stderr, "No Name found in invitation!\n");
384 if(!check_id(name)) {
385 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
389 char filename[PATH_MAX];
390 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
392 FILE *f = fopen(filename, "w");
394 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
398 fprintf(f, "Name = %s\n", name);
400 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
401 FILE *fh = fopen(filename, "w");
403 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
408 // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
409 // Other chunks go unfiltered to their respective host config files
410 const char *p = mesh->data;
413 while((l = get_line(&p))) {
418 // Split line into variable and value
419 int len = strcspn(l, "\t =");
421 value += strspn(value, "\t ");
424 value += strspn(value, "\t ");
429 if(!strcasecmp(l, "Name"))
430 if(strcmp(value, name))
434 else if(!strcasecmp(l, "NetName"))
437 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
440 for(i = 0; variables[i].name; i++) {
441 if(strcasecmp(l, variables[i].name))
447 // Ignore unknown and unsafe variables
449 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
451 } else if(!(variables[i].type & VAR_SAFE)) {
452 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
456 // Copy the safe variable to the right config file
457 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
462 while(l && !strcasecmp(l, "Name")) {
463 if(!check_id(value)) {
464 fprintf(stderr, "Invalid Name found in invitation.\n");
468 if(!strcmp(value, name)) {
469 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
473 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
474 f = fopen(filename, "w");
477 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
481 while((l = get_line(&p))) {
482 if(!strcmp(l, "#---------------------------------------------------------------#"))
484 int len = strcspn(l, "\t =");
485 if(len == 4 && !strncasecmp(l, "Name", 4)) {
487 value += strspn(value, "\t ");
490 value += strspn(value, "\t ");
503 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
507 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
508 fprintf(fh, "Port = %s\n", mesh->myport);
512 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
515 free(mesh->self->name);
516 free(mesh->self->connection->name);
517 mesh->self->name = xstrdup(name);
518 mesh->self->connection->name = name;
520 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
522 load_all_nodes(mesh);
527 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
528 meshlink_handle_t* mesh = handle;
530 int result = send(mesh->sock, data, len, 0);
531 if(result == -1 && errno == EINTR)
541 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
542 meshlink_handle_t* mesh = handle;
544 case SPTPS_HANDSHAKE:
545 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
548 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
549 memcpy(mesh->data + mesh->thedatalen, msg, len);
550 mesh->thedatalen += len;
551 mesh->data[mesh->thedatalen] = 0;
555 return finalize_join(mesh);
558 fprintf(stderr, "Invitation succesfully accepted.\n");
559 shutdown(mesh->sock, SHUT_RDWR);
560 mesh->success = true;
570 static bool recvline(meshlink_handle_t* mesh, size_t len) {
571 char *newline = NULL;
576 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
577 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
578 if(result == -1 && errno == EINTR)
582 mesh->blen += result;
585 if(newline - mesh->buffer >= len)
588 len = newline - mesh->buffer;
590 memcpy(mesh->line, mesh->buffer, len);
592 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
593 mesh->blen -= len + 1;
597 static bool sendline(int fd, char *format, ...) {
598 static char buffer[4096];
603 va_start(ap, format);
604 blen = vsnprintf(buffer, sizeof buffer, format, ap);
607 if(blen < 1 || blen >= sizeof buffer)
614 int result = send(fd, p, blen, MSG_NOSIGNAL);
615 if(result == -1 && errno == EINTR)
626 static const char *errstr[] = {
627 [MESHLINK_OK] = "No error",
628 [MESHLINK_ENOMEM] = "Out of memory",
629 [MESHLINK_ENOENT] = "No such node",
632 const char *meshlink_strerror(meshlink_errno_t err) {
636 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
639 char pubname[PATH_MAX], privname[PATH_MAX];
641 fprintf(stderr, "Generating ECDSA keypair:\n");
643 if(!(key = ecdsa_generate())) {
644 fprintf(stderr, "Error during key generation!\n");
647 fprintf(stderr, "Done.\n");
649 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
650 f = fopen(privname, "w");
656 fchmod(fileno(f), 0600);
659 if(!ecdsa_write_pem_private_key(key, f)) {
660 fprintf(stderr, "Error writing private key!\n");
669 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
670 f = fopen(pubname, "a");
675 char *pubkey = ecdsa_get_base64_public_key(key);
676 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
685 static bool meshlink_setup(meshlink_handle_t *mesh) {
686 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
687 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
691 char filename[PATH_MAX];
692 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
694 if(mkdir(filename, 0777) && errno != EEXIST) {
695 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
699 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
701 if(!access(filename, F_OK)) {
702 fprintf(stderr, "Configuration file %s already exists!\n", filename);
706 FILE *f = fopen(filename, "w");
708 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
712 fprintf(f, "Name = %s\n", mesh->name);
715 if(!ecdsa_keygen(mesh))
723 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
724 // Validate arguments provided by the application
725 bool usingname = false;
727 if(!confbase || !*confbase) {
728 fprintf(stderr, "No confbase given!\n");
732 if(!name || !*name) {
733 fprintf(stderr, "No name given!\n");
736 else { //check name only if there is a name != NULL
738 if(!check_id(name)) {
739 fprintf(stderr, "Invalid name given!\n");
741 } else { usingname = true;}
744 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
745 mesh->confbase = xstrdup(confbase);
746 if (usingname) mesh->name = xstrdup(name);
747 pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
748 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
749 mesh->threadstarted = false;
750 event_loop_init(&mesh->loop);
751 mesh->loop.data = mesh;
753 // TODO: should be set by a function.
754 mesh->debug_level = 5;
756 // Check whether meshlink.conf already exists
758 char filename[PATH_MAX];
759 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
761 if(access(filename, R_OK)) {
762 if(errno == ENOENT) {
764 meshlink_setup(mesh);
766 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
767 return meshlink_close(mesh), NULL;
771 // Read the configuration
773 init_configuration(&mesh->config);
775 if(!read_server_config(mesh))
776 return meshlink_close(mesh), NULL;
779 struct WSAData wsa_state;
780 WSAStartup(MAKEWORD(2, 2), &wsa_state);
783 // Setup up everything
784 // TODO: we should not open listening sockets yet
786 if(!setup_network(mesh))
787 return meshlink_close(mesh), NULL;
792 static void *meshlink_main_loop(void *arg) {
793 meshlink_handle_t *mesh = arg;
795 try_outgoing_connections(mesh);
802 bool meshlink_start(meshlink_handle_t *mesh) {
806 // TODO: open listening sockets first
808 //Check that a valid name is set
810 fprintf(stderr, "No name given!\n");
814 // Start the main thread
816 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
817 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
818 memset(&mesh->thread, 0, sizeof mesh->thread);
822 mesh->threadstarted=true;
827 void meshlink_stop(meshlink_handle_t *mesh) {
831 // Shut down the listening sockets to signal the main thread to shut down
833 for(int i = 0; i < mesh->listen_sockets; i++) {
834 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
835 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
838 // Wait for the main thread to finish
840 pthread_join(mesh->thread, NULL);
843 void meshlink_close(meshlink_handle_t *mesh) {
844 if(!mesh || !mesh->confbase)
847 // Close and free all resources used.
849 close_network_connections(mesh);
851 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
853 exit_configuration(&mesh->config);
854 event_loop_exit(&mesh->loop);
861 ecdsa_free(mesh->invitation_key);
864 free(mesh->confbase);
866 memset(mesh, 0, sizeof *mesh);
871 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
874 mesh->receive_cb = cb;
877 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
880 mesh->node_status_cb = cb;
883 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
887 mesh->log_level = level;
890 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
891 if(!mesh || !destination)
898 /* If there is no outgoing list yet, create one. */
900 if(!mesh->outpacketqueue)
901 mesh->outpacketqueue = list_alloc(NULL);
903 //add packet to the queue
904 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
905 packet_in_queue->destination=destination;
906 packet_in_queue->data=data;
907 packet_in_queue->len=len;
908 pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
909 list_insert_head(mesh->outpacketqueue,packet_in_queue);
910 pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
913 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
917 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
919 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
921 outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
923 list_delete_tail(mesh->outpacketqueue);
926 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
931 packet.probe = false;
932 memset(hdr, 0, sizeof *hdr);
933 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
934 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
936 packet.len = sizeof *hdr + p->len;
937 memcpy(packet.data + sizeof *hdr, p->data, p->len);
939 mesh->self->in_packets++;
940 mesh->self->in_bytes += packet.len;
941 route(mesh, mesh->self, &packet);
945 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
948 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
951 ssize_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
952 if(!mesh || (nmemb && !nodes))
958 pthread_mutex_lock(&(mesh->nodes_mutex));
960 for splay_each(node_t, n, mesh->nodes) {
962 nodes[i] = (meshlink_node_t *)n;
966 pthread_mutex_unlock(&(mesh->nodes_mutex));
971 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
972 if(!mesh || !data || !len || !signature || !siglen)
974 if(*siglen < MESHLINK_SIGLEN)
976 if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature))
978 *siglen = MESHLINK_SIGLEN;
982 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
983 if(!mesh || !data || !len || !signature)
985 if(siglen != MESHLINK_SIGLEN)
987 struct node_t *n = (struct node_t *)source;
988 node_read_ecdsa_public_key(mesh, n);
991 return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
994 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
995 char filename[PATH_MAX];
997 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
998 if(mkdir(filename, 0700) && errno != EEXIST) {
999 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1003 // Count the number of valid invitations, clean up old ones
1004 DIR *dir = opendir(filename);
1006 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1013 time_t deadline = time(NULL) - 604800; // 1 week in the past
1015 while((ent = readdir(dir))) {
1016 if(strlen(ent->d_name) != 24)
1018 char invname[PATH_MAX];
1020 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1021 if(!stat(invname, &st)) {
1022 if(mesh->invitation_key && deadline < st.st_mtime)
1027 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1033 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1040 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1042 // Remove the key if there are no outstanding invitations.
1045 if(mesh->invitation_key) {
1046 ecdsa_free(mesh->invitation_key);
1047 mesh->invitation_key = NULL;
1051 if(mesh->invitation_key)
1054 // Create a new key if necessary.
1055 FILE *f = fopen(filename, "r");
1057 if(errno != ENOENT) {
1058 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1062 mesh->invitation_key = ecdsa_generate();
1063 if(!mesh->invitation_key) {
1064 fprintf(stderr, "Could not generate a new key!\n");
1067 f = fopen(filename, "w");
1069 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1072 chmod(filename, 0600);
1073 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1076 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1078 if(!mesh->invitation_key)
1079 fprintf(stderr, "Could not read private key from %s\n", filename);
1082 return mesh->invitation_key;
1085 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1086 if(!mesh || !address)
1089 for(const char *p = address; *p; p++) {
1090 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1092 fprintf(stderr, "Invalid character in address: %s\n", address);
1096 return append_config_file(mesh, mesh->self->name, "Address", address);
1099 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1103 // Check validity of the new node's name
1104 if(!check_id(name)) {
1105 fprintf(stderr, "Invalid name for node.\n");
1109 // Ensure no host configuration file with that name exists
1110 char filename[PATH_MAX];
1111 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1112 if(!access(filename, F_OK)) {
1113 fprintf(stderr, "A host config file for %s already exists!\n", name);
1117 // Ensure no other nodes know about this name
1118 if(meshlink_get_node(mesh, name)) {
1119 fprintf(stderr, "A node with name %s is already known!\n", name);
1123 // Get the local address
1124 char *address = get_my_hostname(mesh);
1126 fprintf(stderr, "No Address known for ourselves!\n");
1130 if(!refresh_invitation_key(mesh))
1135 // Create a hash of the key.
1136 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1137 sha512(fingerprint, strlen(fingerprint), hash);
1138 b64encode_urlsafe(hash, hash, 18);
1140 // Create a random cookie for this invitation.
1142 randomize(cookie, 18);
1144 // Create a filename that doesn't reveal the cookie itself
1145 char buf[18 + strlen(fingerprint)];
1146 char cookiehash[64];
1147 memcpy(buf, cookie, 18);
1148 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1149 sha512(buf, sizeof buf, cookiehash);
1150 b64encode_urlsafe(cookiehash, cookiehash, 18);
1152 b64encode_urlsafe(cookie, cookie, 18);
1156 // Create a file containing the details of the invitation.
1157 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1158 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1160 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1163 FILE *f = fdopen(ifd, "w");
1167 // Fill in the details.
1168 fprintf(f, "Name = %s\n", name);
1170 // fprintf(f, "NetName = %s\n", netname);
1171 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1173 // Copy Broadcast and Mode
1174 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1175 FILE *tc = fopen(filename, "r");
1178 while(fgets(buf, sizeof buf, tc)) {
1179 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1180 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1182 // Make sure there is a newline character.
1183 if(!strchr(buf, '\n'))
1189 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1193 fprintf(f, "#---------------------------------------------------------------#\n");
1194 fprintf(f, "Name = %s\n", mesh->self->name);
1196 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1200 // Create an URL from the local address, key hash and cookie
1202 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1208 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1209 if(!mesh || !invitation)
1212 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1213 char copy[strlen(invitation) + 1];
1214 strcpy(copy, invitation);
1216 // Split the invitation URL into hostname, port, key hash and cookie.
1218 char *slash = strchr(copy, '/');
1224 if(strlen(slash) != 48)
1227 char *address = copy;
1229 if(*address == '[') {
1231 char *bracket = strchr(address, ']');
1235 if(bracket[1] == ':')
1238 port = strchr(address, ':');
1246 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1249 // Generate a throw-away key for the invitation.
1250 ecdsa_t *key = ecdsa_generate();
1254 char *b64key = ecdsa_get_base64_public_key(key);
1256 //Before doing meshlink_join make sure we are not connected to another mesh
1257 if ( mesh->threadstarted ){
1261 // Connect to the meshlink daemon mentioned in the URL.
1262 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1266 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1267 if(mesh->sock <= 0) {
1268 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1273 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1274 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1275 closesocket(mesh->sock);
1282 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1284 // Tell him we have an invitation, and give him our throw-away key.
1288 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1289 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1290 closesocket(mesh->sock);
1296 char hisname[4096] = "";
1297 int code, hismajor, hisminor = 0;
1299 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) {
1300 fprintf(stderr, "Cannot read greeting from peer\n");
1301 closesocket(mesh->sock);
1305 // Check if the hash of the key he gave us matches the hash in the URL.
1306 char *fingerprint = mesh->line + 2;
1308 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1309 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1312 if(memcmp(hishash, mesh->hash, 18)) {
1313 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1318 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1322 // Start an SPTPS session
1323 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1326 // Feed rest of input buffer to SPTPS
1327 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1332 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1336 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1340 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1344 sptps_stop(&mesh->sptps);
1347 closesocket(mesh->sock);
1349 if(!mesh->success) {
1350 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1357 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1361 char *meshlink_export(meshlink_handle_t *mesh) {
1365 char filename[PATH_MAX];
1366 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1367 FILE *f = fopen(filename, "r");
1369 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1373 fseek(f, 0, SEEK_END);
1374 int fsize = ftell(f);
1377 size_t len = fsize + 9 + strlen(mesh->self->name);
1378 char *buf = xmalloc(len);
1379 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1380 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1381 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1391 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1395 if(strncmp(data, "Name = ", 7)) {
1396 fprintf(stderr, "Invalid data\n");
1400 char *end = strchr(data + 7, '\n');
1402 fprintf(stderr, "Invalid data\n");
1406 int len = end - (data + 7);
1408 memcpy(name, data + 7, len);
1410 if(!check_id(name)) {
1411 fprintf(stderr, "Invalid Name\n");
1415 char filename[PATH_MAX];
1416 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1417 if(!access(filename, F_OK)) {
1418 fprintf(stderr, "File %s already exists, not importing\n", filename);
1422 if(errno != ENOENT) {
1423 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1427 FILE *f = fopen(filename, "w");
1429 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1433 fwrite(end + 1, strlen(end + 1), 1, f);
1436 load_all_nodes(mesh);
1441 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1447 n->status.blacklisted=true;
1448 fprintf(stderr, "Blacklisted %s.\n",node->name);
1450 //Make blacklisting persistent in the config file
1451 append_config_file(mesh, n->name, "blacklisted", "yes");
1456 static void __attribute__((constructor)) meshlink_init(void) {
1460 static void __attribute__((destructor)) meshlink_exit(void) {