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.
241 // fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
248 fprintf(stderr, "Please enter your host's external address or hostname");
250 fprintf(stderr, " [%s]", hostname);
251 fprintf(stderr, ": ");
253 if(!fgets(line, sizeof line, stdin)) {
254 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
266 for(char *p = line; *p; p++) {
267 if(isalnum(*p) || *p == '-' || *p == '.')
269 fprintf(stderr, "Invalid address or hostname.\n");
274 hostname = xstrdup(line);
277 f = fopen(filename, "a");
279 fprintf(f, "\nAddress = %s\n", hostname);
282 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
287 if(strchr(hostname, ':'))
288 xasprintf(&hostport, "[%s]:%s", hostname, port);
290 xasprintf(&hostport, "%s:%s", hostname, port);
292 if(strchr(hostname, ':'))
293 xasprintf(&hostport, "[%s]", hostname);
295 hostport = xstrdup(hostname);
303 static char *get_line(const char **data) {
312 static char line[1024];
313 const char *end = strchr(*data, '\n');
314 size_t len = end ? end - *data : strlen(*data);
315 if(len >= sizeof line) {
316 fprintf(stderr, "Maximum line length exceeded!\n");
319 if(len && !isprint(**data))
322 memcpy(line, *data, len);
333 static char *get_value(const char *data, const char *var) {
334 char *line = get_line(&data);
338 char *sep = line + strcspn(line, " \t=");
339 char *val = sep + strspn(sep, " \t");
341 val += 1 + strspn(val + 1, " \t");
343 if(strcasecmp(line, var))
348 static bool try_bind(int port) {
349 struct addrinfo *ai = NULL;
350 struct addrinfo hint = {
351 .ai_flags = AI_PASSIVE,
352 .ai_family = AF_UNSPEC,
353 .ai_socktype = SOCK_STREAM,
354 .ai_protocol = IPPROTO_TCP,
358 snprintf(portstr, sizeof portstr, "%d", port);
360 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
364 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
367 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
377 static int check_port(meshlink_handle_t *mesh) {
381 fprintf(stderr, "Warning: could not bind to port 655.\n");
383 for(int i = 0; i < 100; i++) {
384 int port = 0x1000 + (rand() & 0x7fff);
386 char filename[PATH_MAX];
387 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
388 FILE *f = fopen(filename, "a");
390 fprintf(stderr, "Please change MeshLink's Port manually.\n");
394 fprintf(f, "Port = %d\n", port);
396 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
401 fprintf(stderr, "Please change MeshLink's Port manually.\n");
405 static bool finalize_join(meshlink_handle_t *mesh) {
406 char *name = xstrdup(get_value(mesh->data, "Name"));
408 fprintf(stderr, "No Name found in invitation!\n");
412 if(!check_id(name)) {
413 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
417 char filename[PATH_MAX];
418 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
420 FILE *f = fopen(filename, "w");
422 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
426 fprintf(f, "Name = %s\n", name);
428 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
429 FILE *fh = fopen(filename, "w");
431 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
436 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
437 // Other chunks go unfiltered to their respective host config files
438 const char *p = mesh->data;
441 while((l = get_line(&p))) {
446 // Split line into variable and value
447 int len = strcspn(l, "\t =");
449 value += strspn(value, "\t ");
452 value += strspn(value, "\t ");
457 if(!strcasecmp(l, "Name"))
458 if(strcmp(value, name))
462 else if(!strcasecmp(l, "NetName"))
465 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
468 for(i = 0; variables[i].name; i++) {
469 if(strcasecmp(l, variables[i].name))
475 // Ignore unknown and unsafe variables
477 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
479 } else if(!(variables[i].type & VAR_SAFE)) {
480 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
484 // Copy the safe variable to the right config file
485 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
490 while(l && !strcasecmp(l, "Name")) {
491 if(!check_id(value)) {
492 fprintf(stderr, "Invalid Name found in invitation.\n");
496 if(!strcmp(value, name)) {
497 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
501 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
502 f = fopen(filename, "w");
505 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
509 while((l = get_line(&p))) {
510 if(!strcmp(l, "#---------------------------------------------------------------#"))
512 int len = strcspn(l, "\t =");
513 if(len == 4 && !strncasecmp(l, "Name", 4)) {
515 value += strspn(value, "\t ");
518 value += strspn(value, "\t ");
531 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
535 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
536 fprintf(fh, "Port = %s\n", mesh->myport);
540 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
543 free(mesh->self->name);
544 free(mesh->self->connection->name);
545 mesh->self->name = xstrdup(name);
546 mesh->self->connection->name = xstrdup(name);
548 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
550 load_all_nodes(mesh);
555 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
556 meshlink_handle_t* mesh = handle;
558 int result = send(mesh->sock, data, len, 0);
559 if(result == -1 && errno == EINTR)
569 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
570 meshlink_handle_t* mesh = handle;
572 case SPTPS_HANDSHAKE:
573 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
576 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
577 memcpy(mesh->data + mesh->thedatalen, msg, len);
578 mesh->thedatalen += len;
579 mesh->data[mesh->thedatalen] = 0;
583 return finalize_join(mesh);
586 fprintf(stderr, "Invitation succesfully accepted.\n");
587 shutdown(mesh->sock, SHUT_RDWR);
588 mesh->success = true;
598 static bool recvline(meshlink_handle_t* mesh, size_t len) {
599 char *newline = NULL;
604 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
605 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
606 if(result == -1 && errno == EINTR)
610 mesh->blen += result;
613 if(newline - mesh->buffer >= len)
616 len = newline - mesh->buffer;
618 memcpy(mesh->line, mesh->buffer, len);
620 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
621 mesh->blen -= len + 1;
625 static bool sendline(int fd, char *format, ...) {
626 static char buffer[4096];
631 va_start(ap, format);
632 blen = vsnprintf(buffer, sizeof buffer, format, ap);
635 if(blen < 1 || blen >= sizeof buffer)
642 int result = send(fd, p, blen, MSG_NOSIGNAL);
643 if(result == -1 && errno == EINTR)
654 static const char *errstr[] = {
655 [MESHLINK_OK] = "No error",
656 [MESHLINK_ENOMEM] = "Out of memory",
657 [MESHLINK_ENOENT] = "No such node",
660 const char *meshlink_strerror(meshlink_errno_t errno) {
661 return errstr[errno];
664 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
667 char pubname[PATH_MAX], privname[PATH_MAX];
669 fprintf(stderr, "Generating ECDSA keypair:\n");
671 if(!(key = ecdsa_generate())) {
672 fprintf(stderr, "Error during key generation!\n");
675 fprintf(stderr, "Done.\n");
677 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
678 f = fopen(privname, "w");
684 fchmod(fileno(f), 0600);
687 if(!ecdsa_write_pem_private_key(key, f)) {
688 fprintf(stderr, "Error writing private key!\n");
697 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
698 f = fopen(pubname, "a");
703 char *pubkey = ecdsa_get_base64_public_key(key);
704 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
713 static bool meshlink_setup(meshlink_handle_t *mesh) {
714 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
715 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
719 char filename[PATH_MAX];
720 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
722 if(mkdir(filename, 0777) && errno != EEXIST) {
723 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
727 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
729 if(!access(filename, F_OK)) {
730 fprintf(stderr, "Configuration file %s already exists!\n", filename);
734 FILE *f = fopen(filename, "w");
736 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
740 fprintf(f, "Name = %s\n", mesh->name);
743 if(!ecdsa_keygen(mesh))
751 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
752 // Validate arguments provided by the application
754 if(!confbase || !*confbase) {
755 fprintf(stderr, "No confbase given!\n");
759 if(!name || !*name) {
760 fprintf(stderr, "No name given!\n");
764 if(!check_id(name)) {
765 fprintf(stderr, "Invalid name given!\n");
769 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
770 mesh->confbase = xstrdup(confbase);
771 mesh->name = xstrdup(name);
772 event_loop_init(&mesh->loop);
773 mesh->loop.data = mesh;
775 // TODO: should be set by a function.
776 mesh->debug_level = 5;
778 // Check whether meshlink.conf already exists
780 char filename[PATH_MAX];
781 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
783 if(access(filename, R_OK)) {
784 if(errno == ENOENT) {
786 meshlink_setup(mesh);
788 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
789 return meshlink_close(mesh), NULL;
793 // Read the configuration
795 init_configuration(&mesh->config);
797 if(!read_server_config(mesh))
798 return meshlink_close(mesh), NULL;
801 struct WSAData wsa_state;
802 WSAStartup(MAKEWORD(2, 2), &wsa_state);
805 // Setup up everything
806 // TODO: we should not open listening sockets yet
808 if(!setup_network(mesh))
809 return meshlink_close(mesh), NULL;
814 void *meshlink_main_loop(void *arg) {
815 meshlink_handle_t *mesh = arg;
817 try_outgoing_connections(mesh);
824 bool meshlink_start(meshlink_handle_t *mesh) {
825 // TODO: open listening sockets first
827 // Start the main thread
829 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
830 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
831 memset(&mesh->thread, 0, sizeof mesh->thread);
838 void meshlink_stop(meshlink_handle_t *mesh) {
839 // Shut down the listening sockets to signal the main thread to shut down
841 for(int i = 0; i < mesh->listen_sockets; i++) {
842 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
843 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
846 // Wait for the main thread to finish
848 pthread_join(mesh->thread, NULL);
851 void meshlink_close(meshlink_handle_t *mesh) {
852 // Close and free all resources used.
854 close_network_connections(mesh);
856 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
858 exit_configuration(&mesh->config);
859 event_loop_exit(&mesh->loop);
866 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
867 mesh->receive_cb = cb;
870 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
871 mesh->node_status_cb = cb;
874 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
876 mesh->log_level = level;
879 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
881 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
882 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
887 packet.probe = false;
888 memset(hdr, 0, sizeof *hdr);
889 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
890 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
892 packet.len = sizeof *hdr + len;
893 memcpy(packet.data + sizeof *hdr, data, len);
895 mesh->self->in_packets++;
896 mesh->self->in_bytes += packet.len;
897 route(mesh, mesh->self, &packet);
901 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
902 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
905 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
908 for splay_each(node_t, n, mesh->nodes) {
910 nodes[i] = (meshlink_node_t *)n;
917 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
921 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
925 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
926 char filename[PATH_MAX];
928 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
929 if(mkdir(filename, 0700) && errno != EEXIST) {
930 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
934 // Count the number of valid invitations, clean up old ones
935 DIR *dir = opendir(filename);
937 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
944 time_t deadline = time(NULL) - 604800; // 1 week in the past
946 while((ent = readdir(dir))) {
947 if(strlen(ent->d_name) != 24)
949 char invname[PATH_MAX];
951 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
952 if(!stat(invname, &st)) {
953 if(mesh->invitation_key && deadline < st.st_mtime)
958 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
964 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
971 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
973 // Remove the key if there are no outstanding invitations.
976 if(mesh->invitation_key) {
977 ecdsa_free(mesh->invitation_key);
978 mesh->invitation_key = NULL;
982 if(mesh->invitation_key)
985 // Create a new key if necessary.
986 FILE *f = fopen(filename, "r");
988 if(errno != ENOENT) {
989 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
993 mesh->invitation_key = ecdsa_generate();
994 if(!mesh->invitation_key) {
995 fprintf(stderr, "Could not generate a new key!\n");
998 f = fopen(filename, "w");
1000 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1003 chmod(filename, 0600);
1004 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1007 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1009 if(!mesh->invitation_key)
1010 fprintf(stderr, "Could not read private key from %s\n", filename);
1013 return mesh->invitation_key;
1016 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1017 // Check validity of the new node's name
1018 if(!check_id(name)) {
1019 fprintf(stderr, "Invalid name for node.\n");
1023 // Ensure no host configuration file with that name exists
1024 char filename[PATH_MAX];
1025 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1026 if(!access(filename, F_OK)) {
1027 fprintf(stderr, "A host config file for %s already exists!\n", name);
1031 // Ensure no other nodes know about this name
1032 if(meshlink_get_node(mesh, name)) {
1033 fprintf(stderr, "A node with name %s is already known!\n", name);
1037 if(!refresh_invitation_key(mesh))
1042 // Create a hash of the key.
1043 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1044 sha512(fingerprint, strlen(fingerprint), hash);
1045 b64encode_urlsafe(hash, hash, 18);
1047 // Create a random cookie for this invitation.
1049 randomize(cookie, 18);
1051 // Create a filename that doesn't reveal the cookie itself
1052 char buf[18 + strlen(fingerprint)];
1053 char cookiehash[64];
1054 memcpy(buf, cookie, 18);
1055 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1056 sha512(buf, sizeof buf, cookiehash);
1057 b64encode_urlsafe(cookiehash, cookiehash, 18);
1059 b64encode_urlsafe(cookie, cookie, 18);
1061 // Create a file containing the details of the invitation.
1062 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1063 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1065 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1068 FILE *f = fdopen(ifd, "w");
1072 // Get the local address
1073 char *address = get_my_hostname(mesh);
1075 // Fill in the details.
1076 fprintf(f, "Name = %s\n", name);
1078 // fprintf(f, "NetName = %s\n", netname);
1079 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1081 // Copy Broadcast and Mode
1082 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1083 FILE *tc = fopen(filename, "r");
1086 while(fgets(buf, sizeof buf, tc)) {
1087 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1088 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1090 // Make sure there is a newline character.
1091 if(!strchr(buf, '\n'))
1097 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1101 fprintf(f, "#---------------------------------------------------------------#\n");
1102 fprintf(f, "Name = %s\n", mesh->self->name);
1104 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1108 // Create an URL from the local address, key hash and cookie
1110 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1115 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1116 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1117 char copy[strlen(invitation) + 1];
1118 strcpy(copy, invitation);
1120 // Split the invitation URL into hostname, port, key hash and cookie.
1122 char *slash = strchr(copy, '/');
1128 if(strlen(slash) != 48)
1131 char *address = copy;
1133 if(*address == '[') {
1135 char *bracket = strchr(address, ']');
1139 if(bracket[1] == ':')
1142 port = strchr(address, ':');
1150 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1153 // Generate a throw-away key for the invitation.
1154 ecdsa_t *key = ecdsa_generate();
1158 char *b64key = ecdsa_get_base64_public_key(key);
1160 // Connect to the meshlink daemon mentioned in the URL.
1161 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1165 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1166 if(mesh->sock <= 0) {
1167 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1171 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1172 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1173 closesocket(mesh->sock);
1177 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1179 // Tell him we have an invitation, and give him our throw-away key.
1183 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1184 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1185 closesocket(mesh->sock);
1189 char hisname[4096] = "";
1190 int code, hismajor, hisminor = 0;
1192 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) {
1193 fprintf(stderr, "Cannot read greeting from peer\n");
1194 closesocket(mesh->sock);
1198 // Check if the hash of the key he gave us matches the hash in the URL.
1199 char *fingerprint = mesh->line + 2;
1201 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1202 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1205 if(memcmp(hishash, mesh->hash, 18)) {
1206 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1211 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1215 // Start an SPTPS session
1216 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1219 // Feed rest of input buffer to SPTPS
1220 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1225 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1229 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1233 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1237 sptps_stop(&mesh->sptps);
1240 closesocket(mesh->sock);
1242 if(!mesh->success) {
1243 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1250 fprintf(stderr, "Invalid invitation URL.\n");
1254 char *meshlink_export(meshlink_handle_t *mesh) {
1258 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1262 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1265 n->status.blacklisted=true;
1266 fprintf(stderr, "Blacklisted %s.\n",node->name);
1268 //Make blacklisting persistent in the config file
1269 append_config_file(mesh, n->name, "blacklisted", "yes");
1274 static void __attribute__((constructor)) meshlink_init(void) {
1278 static void __attribute__((destructor)) meshlink_exit(void) {