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 tinc.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 //TODO: this can go away completely
48 const var_t variables[] = {
49 /* Server configuration */
50 {"AddressFamily", VAR_SERVER},
51 {"AutoConnect", VAR_SERVER | VAR_SAFE},
52 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
53 {"BindToInterface", VAR_SERVER},
54 {"Broadcast", VAR_SERVER | VAR_SAFE},
55 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
56 {"DecrementTTL", VAR_SERVER},
57 {"Device", VAR_SERVER},
58 {"DeviceType", VAR_SERVER},
59 {"DirectOnly", VAR_SERVER},
60 {"ECDSAPrivateKeyFile", VAR_SERVER},
61 {"ExperimentalProtocol", VAR_SERVER},
62 {"Forwarding", VAR_SERVER},
63 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
64 {"Hostnames", VAR_SERVER},
65 {"IffOneQueue", VAR_SERVER},
66 {"Interface", VAR_SERVER},
67 {"KeyExpire", VAR_SERVER},
68 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
69 {"LocalDiscovery", VAR_SERVER},
70 {"MACExpire", VAR_SERVER},
71 {"MaxConnectionBurst", VAR_SERVER},
72 {"MaxOutputBufferSize", VAR_SERVER},
73 {"MaxTimeout", VAR_SERVER},
74 {"Mode", VAR_SERVER | VAR_SAFE},
76 {"PingInterval", VAR_SERVER},
77 {"PingTimeout", VAR_SERVER},
78 {"PriorityInheritance", VAR_SERVER},
79 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
80 {"PrivateKeyFile", VAR_SERVER},
81 {"ProcessPriority", VAR_SERVER},
82 {"Proxy", VAR_SERVER},
83 {"ReplayWindow", VAR_SERVER},
84 {"ScriptsExtension", VAR_SERVER},
85 {"ScriptsInterpreter", VAR_SERVER},
86 {"StrictSubnets", VAR_SERVER},
87 {"TunnelServer", VAR_SERVER},
88 {"VDEGroup", VAR_SERVER},
89 {"VDEPort", VAR_SERVER},
90 /* Host configuration */
91 {"Address", VAR_HOST | VAR_MULTIPLE},
92 {"Cipher", VAR_SERVER | VAR_HOST},
93 {"ClampMSS", VAR_SERVER | VAR_HOST},
94 {"Compression", VAR_SERVER | VAR_HOST},
95 {"Digest", VAR_SERVER | VAR_HOST},
96 {"ECDSAPublicKey", VAR_HOST},
97 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
98 {"IndirectData", VAR_SERVER | VAR_HOST},
99 {"MACLength", VAR_SERVER | VAR_HOST},
100 {"PMTU", VAR_SERVER | VAR_HOST},
101 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
103 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
104 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
105 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
106 {"TCPOnly", VAR_SERVER | VAR_HOST},
107 {"Weight", VAR_HOST | VAR_SAFE},
111 static bool fcopy(FILE *out, const char *filename) {
112 FILE *in = fopen(filename, "r");
114 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
120 while((len = fread(buf, 1, sizeof buf, in)))
121 fwrite(buf, len, 1, out);
126 static int rstrip(char *value) {
127 int len = strlen(value);
128 while(len && strchr("\t\r\n ", value[len - 1]))
133 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
135 if(!filename || (*hostname && *port))
138 FILE *f = fopen(filename, "r");
142 while(fgets(line, sizeof line, f)) {
146 p += strcspn(p, "\t =");
149 q = p + strspn(p, "\t ");
151 q += 1 + strspn(q + 1, "\t ");
153 p = q + strcspn(q, "\t ");
156 p += strspn(p, "\t ");
157 p[strcspn(p, "\t ")] = 0;
159 if(!*port && !strcasecmp(line, "Port")) {
161 } else if(!*hostname && !strcasecmp(line, "Address")) {
162 *hostname = xstrdup(q);
169 if(*hostname && *port)
175 static char *get_my_hostname(meshlink_handle_t* mesh) {
176 char *hostname = NULL;
178 char *hostport = NULL;
179 char *name = mesh->self->name;
180 char filename[PATH_MAX] = "";
184 // Use first Address statement in own host config file
185 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
186 scan_for_hostname(filename, &hostname, &port);
191 // If that doesn't work, guess externally visible hostname
192 fprintf(stderr, "Trying to discover externally visible hostname...\n");
193 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
194 struct addrinfo *aip = ai;
195 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
198 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
200 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
206 send(s, request, sizeof request - 1, 0);
207 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
210 if(line[len - 1] == '\n')
212 char *p = strrchr(line, '\n');
214 hostname = xstrdup(p + 1);
227 // Check that the hostname is reasonable
229 for(char *p = hostname; *p; p++) {
230 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
232 // If not, forget it.
242 f = fopen(filename, "a");
244 fprintf(f, "\nAddress = %s\n", hostname);
247 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
252 if(strchr(hostname, ':'))
253 xasprintf(&hostport, "[%s]:%s", hostname, port);
255 xasprintf(&hostport, "%s:%s", hostname, port);
257 if(strchr(hostname, ':'))
258 xasprintf(&hostport, "[%s]", hostname);
260 hostport = xstrdup(hostname);
268 static char *get_line(const char **data) {
277 static char line[1024];
278 const char *end = strchr(*data, '\n');
279 size_t len = end ? end - *data : strlen(*data);
280 if(len >= sizeof line) {
281 fprintf(stderr, "Maximum line length exceeded!\n");
284 if(len && !isprint(**data))
287 memcpy(line, *data, len);
298 static char *get_value(const char *data, const char *var) {
299 char *line = get_line(&data);
303 char *sep = line + strcspn(line, " \t=");
304 char *val = sep + strspn(sep, " \t");
306 val += 1 + strspn(val + 1, " \t");
308 if(strcasecmp(line, var))
313 static bool try_bind(int port) {
314 struct addrinfo *ai = NULL;
315 struct addrinfo hint = {
316 .ai_flags = AI_PASSIVE,
317 .ai_family = AF_UNSPEC,
318 .ai_socktype = SOCK_STREAM,
319 .ai_protocol = IPPROTO_TCP,
323 snprintf(portstr, sizeof portstr, "%d", port);
325 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
329 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
332 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
342 static int check_port(meshlink_handle_t *mesh) {
346 fprintf(stderr, "Warning: could not bind to port 655.\n");
348 for(int i = 0; i < 100; i++) {
349 int port = 0x1000 + (rand() & 0x7fff);
351 char filename[PATH_MAX];
352 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
353 FILE *f = fopen(filename, "a");
355 fprintf(stderr, "Please change MeshLink's Port manually.\n");
359 fprintf(f, "Port = %d\n", port);
361 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
366 fprintf(stderr, "Please change MeshLink's Port manually.\n");
370 static bool finalize_join(meshlink_handle_t *mesh) {
371 char *name = xstrdup(get_value(mesh->data, "Name"));
373 fprintf(stderr, "No Name found in invitation!\n");
377 if(!check_id(name)) {
378 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
382 char filename[PATH_MAX];
383 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
385 FILE *f = fopen(filename, "w");
387 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
391 fprintf(f, "Name = %s\n", name);
393 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
394 FILE *fh = fopen(filename, "w");
396 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
401 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
402 // Other chunks go unfiltered to their respective host config files
403 const char *p = mesh->data;
406 while((l = get_line(&p))) {
411 // Split line into variable and value
412 int len = strcspn(l, "\t =");
414 value += strspn(value, "\t ");
417 value += strspn(value, "\t ");
422 if(!strcasecmp(l, "Name"))
423 if(strcmp(value, name))
427 else if(!strcasecmp(l, "NetName"))
430 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
433 for(i = 0; variables[i].name; i++) {
434 if(strcasecmp(l, variables[i].name))
440 // Ignore unknown and unsafe variables
442 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
444 } else if(!(variables[i].type & VAR_SAFE)) {
445 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
449 // Copy the safe variable to the right config file
450 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
455 while(l && !strcasecmp(l, "Name")) {
456 if(!check_id(value)) {
457 fprintf(stderr, "Invalid Name found in invitation.\n");
461 if(!strcmp(value, name)) {
462 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
466 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
467 f = fopen(filename, "w");
470 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
474 while((l = get_line(&p))) {
475 if(!strcmp(l, "#---------------------------------------------------------------#"))
477 int len = strcspn(l, "\t =");
478 if(len == 4 && !strncasecmp(l, "Name", 4)) {
480 value += strspn(value, "\t ");
483 value += strspn(value, "\t ");
496 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
500 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
501 fprintf(fh, "Port = %s\n", mesh->myport);
505 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
508 free(mesh->self->name);
509 free(mesh->self->connection->name);
510 mesh->self->name = xstrdup(name);
511 mesh->self->connection->name = xstrdup(name);
513 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
515 load_all_nodes(mesh);
520 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
521 meshlink_handle_t* mesh = handle;
523 int result = send(mesh->sock, data, len, 0);
524 if(result == -1 && errno == EINTR)
534 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
535 meshlink_handle_t* mesh = handle;
537 case SPTPS_HANDSHAKE:
538 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
541 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
542 memcpy(mesh->data + mesh->thedatalen, msg, len);
543 mesh->thedatalen += len;
544 mesh->data[mesh->thedatalen] = 0;
548 return finalize_join(mesh);
551 fprintf(stderr, "Invitation succesfully accepted.\n");
552 shutdown(mesh->sock, SHUT_RDWR);
553 mesh->success = true;
563 static bool recvline(meshlink_handle_t* mesh, size_t len) {
564 char *newline = NULL;
569 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
570 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
571 if(result == -1 && errno == EINTR)
575 mesh->blen += result;
578 if(newline - mesh->buffer >= len)
581 len = newline - mesh->buffer;
583 memcpy(mesh->line, mesh->buffer, len);
585 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
586 mesh->blen -= len + 1;
590 static bool sendline(int fd, char *format, ...) {
591 static char buffer[4096];
596 va_start(ap, format);
597 blen = vsnprintf(buffer, sizeof buffer, format, ap);
600 if(blen < 1 || blen >= sizeof buffer)
607 int result = send(fd, p, blen, MSG_NOSIGNAL);
608 if(result == -1 && errno == EINTR)
619 static const char *errstr[] = {
620 [MESHLINK_OK] = "No error",
621 [MESHLINK_ENOMEM] = "Out of memory",
622 [MESHLINK_ENOENT] = "No such node",
625 const char *meshlink_strerror(meshlink_errno_t errno) {
626 return errstr[errno];
629 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
632 char pubname[PATH_MAX], privname[PATH_MAX];
634 fprintf(stderr, "Generating ECDSA keypair:\n");
636 if(!(key = ecdsa_generate())) {
637 fprintf(stderr, "Error during key generation!\n");
640 fprintf(stderr, "Done.\n");
642 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
643 f = fopen(privname, "w");
649 fchmod(fileno(f), 0600);
652 if(!ecdsa_write_pem_private_key(key, f)) {
653 fprintf(stderr, "Error writing private key!\n");
662 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
663 f = fopen(pubname, "a");
668 char *pubkey = ecdsa_get_base64_public_key(key);
669 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
678 static bool meshlink_setup(meshlink_handle_t *mesh) {
679 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
680 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
684 char filename[PATH_MAX];
685 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
687 if(mkdir(filename, 0777) && errno != EEXIST) {
688 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
692 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
694 if(!access(filename, F_OK)) {
695 fprintf(stderr, "Configuration file %s already exists!\n", filename);
699 FILE *f = fopen(filename, "w");
701 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
705 fprintf(f, "Name = %s\n", mesh->name);
708 if(!ecdsa_keygen(mesh))
716 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
717 // Validate arguments provided by the application
718 bool usingname = false;
720 if(!confbase || !*confbase) {
721 fprintf(stderr, "No confbase given!\n");
725 if(!name || !*name) {
726 fprintf(stderr, "No name given!\n");
729 else { //check name only if there is a name != NULL
731 if(!check_id(name)) {
732 fprintf(stderr, "Invalid name given!\n");
734 } else { usingname = true;}
737 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
738 mesh->confbase = xstrdup(confbase);
739 if (usingname) mesh->name = xstrdup(name);
740 pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
741 pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
742 mesh->threadstarted = false;
743 event_loop_init(&mesh->loop);
744 mesh->loop.data = mesh;
746 // TODO: should be set by a function.
747 mesh->debug_level = 5;
749 // Check whether meshlink.conf already exists
751 char filename[PATH_MAX];
752 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
754 if(access(filename, R_OK)) {
755 if(errno == ENOENT) {
757 meshlink_setup(mesh);
759 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
760 return meshlink_close(mesh), NULL;
764 // Read the configuration
766 init_configuration(&mesh->config);
768 if(!read_server_config(mesh))
769 return meshlink_close(mesh), NULL;
772 struct WSAData wsa_state;
773 WSAStartup(MAKEWORD(2, 2), &wsa_state);
776 // Setup up everything
777 // TODO: we should not open listening sockets yet
779 if(!setup_network(mesh))
780 return meshlink_close(mesh), NULL;
785 void *meshlink_main_loop(void *arg) {
786 meshlink_handle_t *mesh = arg;
788 try_outgoing_connections(mesh);
795 bool meshlink_start(meshlink_handle_t *mesh) {
796 // TODO: open listening sockets first
798 //Check that a valid name is set
800 fprintf(stderr, "No name given!\n");
804 // Start the main thread
806 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
807 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
808 memset(&mesh->thread, 0, sizeof mesh->thread);
812 mesh->threadstarted=true;
817 void meshlink_stop(meshlink_handle_t *mesh) {
818 // Shut down the listening sockets to signal the main thread to shut down
820 for(int i = 0; i < mesh->listen_sockets; i++) {
821 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
822 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
825 // Wait for the main thread to finish
827 pthread_join(mesh->thread, NULL);
830 void meshlink_close(meshlink_handle_t *mesh) {
831 // Close and free all resources used.
833 close_network_connections(mesh);
835 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
837 exit_configuration(&mesh->config);
838 event_loop_exit(&mesh->loop);
847 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
848 mesh->receive_cb = cb;
851 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
852 mesh->node_status_cb = cb;
855 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
857 mesh->log_level = level;
860 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
862 /* If there is no outgoing list yet, create one. */
864 if(!mesh->outpacketqueue)
865 mesh->outpacketqueue = list_alloc(NULL);
867 //add packet to the queue
868 outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
869 packet_in_queue->destination=destination;
870 packet_in_queue->data=data;
871 packet_in_queue->len=len;
872 pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
873 list_insert_head(mesh->outpacketqueue,packet_in_queue);
874 pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
877 signal_trigger(&(mesh->loop),&(mesh->datafromapp));
881 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
883 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
885 outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
887 list_delete_tail(mesh->outpacketqueue);
890 if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
895 packet.probe = false;
896 memset(hdr, 0, sizeof *hdr);
897 memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
898 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
900 packet.len = sizeof *hdr + p->len;
901 memcpy(packet.data + sizeof *hdr, p->data, p->len);
903 mesh->self->in_packets++;
904 mesh->self->in_bytes += packet.len;
905 route(mesh, mesh->self, &packet);
909 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
910 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
913 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
917 pthread_mutex_lock(&(mesh->nodes_mutex));
919 for splay_each(node_t, n, mesh->nodes) {
921 nodes[i] = (meshlink_node_t *)n;
925 pthread_mutex_unlock(&(mesh->nodes_mutex));
930 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
934 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
938 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
939 char filename[PATH_MAX];
941 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
942 if(mkdir(filename, 0700) && errno != EEXIST) {
943 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
947 // Count the number of valid invitations, clean up old ones
948 DIR *dir = opendir(filename);
950 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
957 time_t deadline = time(NULL) - 604800; // 1 week in the past
959 while((ent = readdir(dir))) {
960 if(strlen(ent->d_name) != 24)
962 char invname[PATH_MAX];
964 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
965 if(!stat(invname, &st)) {
966 if(mesh->invitation_key && deadline < st.st_mtime)
971 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
977 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
984 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
986 // Remove the key if there are no outstanding invitations.
989 if(mesh->invitation_key) {
990 ecdsa_free(mesh->invitation_key);
991 mesh->invitation_key = NULL;
995 if(mesh->invitation_key)
998 // Create a new key if necessary.
999 FILE *f = fopen(filename, "r");
1001 if(errno != ENOENT) {
1002 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1006 mesh->invitation_key = ecdsa_generate();
1007 if(!mesh->invitation_key) {
1008 fprintf(stderr, "Could not generate a new key!\n");
1011 f = fopen(filename, "w");
1013 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1016 chmod(filename, 0600);
1017 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1020 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1022 if(!mesh->invitation_key)
1023 fprintf(stderr, "Could not read private key from %s\n", filename);
1026 return mesh->invitation_key;
1029 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1030 for(const char *p = address; *p; p++) {
1031 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1033 fprintf(stderr, "Invalid character in address: %s\n", address);
1037 return append_config_file(mesh, mesh->self->name, "Address", address);
1040 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1041 // Check validity of the new node's name
1042 if(!check_id(name)) {
1043 fprintf(stderr, "Invalid name for node.\n");
1047 // Ensure no host configuration file with that name exists
1048 char filename[PATH_MAX];
1049 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1050 if(!access(filename, F_OK)) {
1051 fprintf(stderr, "A host config file for %s already exists!\n", name);
1055 // Ensure no other nodes know about this name
1056 if(meshlink_get_node(mesh, name)) {
1057 fprintf(stderr, "A node with name %s is already known!\n", name);
1061 // Get the local address
1062 char *address = get_my_hostname(mesh);
1064 fprintf(stderr, "No Address known for ourselves!\n");
1068 if(!refresh_invitation_key(mesh))
1073 // Create a hash of the key.
1074 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1075 sha512(fingerprint, strlen(fingerprint), hash);
1076 b64encode_urlsafe(hash, hash, 18);
1078 // Create a random cookie for this invitation.
1080 randomize(cookie, 18);
1082 // Create a filename that doesn't reveal the cookie itself
1083 char buf[18 + strlen(fingerprint)];
1084 char cookiehash[64];
1085 memcpy(buf, cookie, 18);
1086 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1087 sha512(buf, sizeof buf, cookiehash);
1088 b64encode_urlsafe(cookiehash, cookiehash, 18);
1090 b64encode_urlsafe(cookie, cookie, 18);
1092 // Create a file containing the details of the invitation.
1093 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1094 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1096 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1099 FILE *f = fdopen(ifd, "w");
1103 // Fill in the details.
1104 fprintf(f, "Name = %s\n", name);
1106 // fprintf(f, "NetName = %s\n", netname);
1107 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1109 // Copy Broadcast and Mode
1110 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1111 FILE *tc = fopen(filename, "r");
1114 while(fgets(buf, sizeof buf, tc)) {
1115 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1116 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1118 // Make sure there is a newline character.
1119 if(!strchr(buf, '\n'))
1125 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1129 fprintf(f, "#---------------------------------------------------------------#\n");
1130 fprintf(f, "Name = %s\n", mesh->self->name);
1132 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1136 // Create an URL from the local address, key hash and cookie
1138 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1143 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1144 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1145 char copy[strlen(invitation) + 1];
1146 strcpy(copy, invitation);
1148 // Split the invitation URL into hostname, port, key hash and cookie.
1150 char *slash = strchr(copy, '/');
1156 if(strlen(slash) != 48)
1159 char *address = copy;
1161 if(*address == '[') {
1163 char *bracket = strchr(address, ']');
1167 if(bracket[1] == ':')
1170 port = strchr(address, ':');
1178 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1181 // Generate a throw-away key for the invitation.
1182 ecdsa_t *key = ecdsa_generate();
1186 char *b64key = ecdsa_get_base64_public_key(key);
1188 //Before doing meshlink_join make sure we are not connected to another mesh
1189 if ( mesh->threadstarted ){
1193 // Connect to the meshlink daemon mentioned in the URL.
1194 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1198 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1199 if(mesh->sock <= 0) {
1200 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1204 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1205 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1206 closesocket(mesh->sock);
1210 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1212 // Tell him we have an invitation, and give him our throw-away key.
1216 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1217 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1218 closesocket(mesh->sock);
1222 char hisname[4096] = "";
1223 int code, hismajor, hisminor = 0;
1225 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) {
1226 fprintf(stderr, "Cannot read greeting from peer\n");
1227 closesocket(mesh->sock);
1231 // Check if the hash of the key he gave us matches the hash in the URL.
1232 char *fingerprint = mesh->line + 2;
1234 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1235 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1238 if(memcmp(hishash, mesh->hash, 18)) {
1239 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1244 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1248 // Start an SPTPS session
1249 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1252 // Feed rest of input buffer to SPTPS
1253 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1258 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1262 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1266 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1270 sptps_stop(&mesh->sptps);
1273 closesocket(mesh->sock);
1275 if(!mesh->success) {
1276 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1283 fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1287 char *meshlink_export(meshlink_handle_t *mesh) {
1288 char filename[PATH_MAX];
1289 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1290 FILE *f = fopen(filename, "r");
1292 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1296 fseek(f, 0, SEEK_END);
1297 int fsize = ftell(f);
1300 size_t len = fsize + 9 + strlen(mesh->self->name);
1301 char *buf = xmalloc(len);
1302 snprintf(buf, len, "Name = %s\n", mesh->self->name);
1303 if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1304 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1314 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1315 if(strncmp(data, "Name = ", 7)) {
1316 fprintf(stderr, "Invalid data\n");
1320 char *end = strchr(data + 7, '\n');
1322 fprintf(stderr, "Invalid data\n");
1326 int len = end - (data + 7);
1328 memcpy(name, data + 7, len);
1330 if(!check_id(name)) {
1331 fprintf(stderr, "Invalid Name\n");
1335 char filename[PATH_MAX];
1336 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1337 if(!access(filename, F_OK)) {
1338 fprintf(stderr, "File %s already exists, not importing\n", filename);
1342 if(errno != ENOENT) {
1343 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1347 FILE *f = fopen(filename, "w");
1349 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1353 fwrite(end + 1, strlen(end + 1), 1, f);
1356 load_all_nodes(mesh);
1361 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1364 n->status.blacklisted=true;
1365 fprintf(stderr, "Blacklisted %s.\n",node->name);
1367 //Make blacklisting persistent in the config file
1368 append_config_file(mesh, n->name, "blacklisted", "yes");
1373 meshlink_connection_t* meshlink_open_rchannel(meshlink_handle_t *mesh, meshlink_node_t *destination, uint16_t dport) {
1375 //TODO: check in mesh->socketsbitmap for a free descriptor and allocate a source port for this connection
1379 for (int i=0; i < 1024 ;i++) {
1380 if (mesh->socketsbitmap.bitValues[i].bit == 0) {
1381 mesh->socketsbitmap.bitValues[i].bit=1;
1387 if (descriptor == -1 ) return NULL;
1389 //TODO: register a callback for the data that will be received from this connection
1391 //TODO: return a description value that the user will use to write on this channel
1395 static void __attribute__((constructor)) meshlink_init(void) {
1399 static void __attribute__((destructor)) meshlink_exit(void) {