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"
39 #include "ed25519/sha512.h"
42 //TODO: this can go away completely
43 const var_t variables[] = {
44 /* Server configuration */
45 {"AddressFamily", VAR_SERVER},
46 {"AutoConnect", VAR_SERVER | VAR_SAFE},
47 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
48 {"BindToInterface", VAR_SERVER},
49 {"Broadcast", VAR_SERVER | VAR_SAFE},
50 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
51 {"DecrementTTL", VAR_SERVER},
52 {"Device", VAR_SERVER},
53 {"DeviceType", VAR_SERVER},
54 {"DirectOnly", VAR_SERVER},
55 {"ECDSAPrivateKeyFile", VAR_SERVER},
56 {"ExperimentalProtocol", VAR_SERVER},
57 {"Forwarding", VAR_SERVER},
58 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
59 {"Hostnames", VAR_SERVER},
60 {"IffOneQueue", VAR_SERVER},
61 {"Interface", VAR_SERVER},
62 {"KeyExpire", VAR_SERVER},
63 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
64 {"LocalDiscovery", VAR_SERVER},
65 {"MACExpire", VAR_SERVER},
66 {"MaxConnectionBurst", VAR_SERVER},
67 {"MaxOutputBufferSize", VAR_SERVER},
68 {"MaxTimeout", VAR_SERVER},
69 {"Mode", VAR_SERVER | VAR_SAFE},
71 {"PingInterval", VAR_SERVER},
72 {"PingTimeout", VAR_SERVER},
73 {"PriorityInheritance", VAR_SERVER},
74 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
75 {"PrivateKeyFile", VAR_SERVER},
76 {"ProcessPriority", VAR_SERVER},
77 {"Proxy", VAR_SERVER},
78 {"ReplayWindow", VAR_SERVER},
79 {"ScriptsExtension", VAR_SERVER},
80 {"ScriptsInterpreter", VAR_SERVER},
81 {"StrictSubnets", VAR_SERVER},
82 {"TunnelServer", VAR_SERVER},
83 {"VDEGroup", VAR_SERVER},
84 {"VDEPort", VAR_SERVER},
85 /* Host configuration */
86 {"Address", VAR_HOST | VAR_MULTIPLE},
87 {"Cipher", VAR_SERVER | VAR_HOST},
88 {"ClampMSS", VAR_SERVER | VAR_HOST},
89 {"Compression", VAR_SERVER | VAR_HOST},
90 {"Digest", VAR_SERVER | VAR_HOST},
91 {"ECDSAPublicKey", VAR_HOST},
92 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
93 {"IndirectData", VAR_SERVER | VAR_HOST},
94 {"MACLength", VAR_SERVER | VAR_HOST},
95 {"PMTU", VAR_SERVER | VAR_HOST},
96 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
98 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
99 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
100 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
101 {"TCPOnly", VAR_SERVER | VAR_HOST},
102 {"Weight", VAR_HOST | VAR_SAFE},
106 static bool fcopy(FILE *out, const char *filename) {
107 FILE *in = fopen(filename, "r");
109 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
115 while((len = fread(buf, 1, sizeof buf, in)))
116 fwrite(buf, len, 1, out);
120 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
122 if(!filename || (*hostname && *port))
125 FILE *f = fopen(filename, "r");
129 while(fgets(line, sizeof line, f)) {
133 p += strcspn(p, "\t =");
136 q = p + strspn(p, "\t ");
138 q += 1 + strspn(q + 1, "\t ");
140 p = q + strcspn(q, "\t ");
143 p += strspn(p, "\t ");
144 p[strcspn(p, "\t ")] = 0;
146 if(!*port && !strcasecmp(line, "Port")) {
148 } else if(!*hostname && !strcasecmp(line, "Address")) {
149 *hostname = xstrdup(q);
156 if(*hostname && *port)
162 static char *get_my_hostname(meshlink_handle_t* mesh) {
163 char *hostname = NULL;
165 char *hostport = NULL;
166 char *name = mesh->self->name;
167 char filename[PATH_MAX];
170 // Use first Address statement in own host config file
171 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
172 scan_for_hostname(filename, &hostname, &port);
173 scan_for_hostname(mesh->meshlink_conf, &hostname, &port);
178 // If that doesn't work, guess externally visible hostname
179 fprintf(stderr, "Trying to discover externally visible hostname...\n");
180 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
181 struct addrinfo *aip = ai;
182 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
185 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
187 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
193 send(s, request, sizeof request - 1, 0);
194 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
197 if(line[len - 1] == '\n')
199 char *p = strrchr(line, '\n');
201 hostname = xstrdup(p + 1);
214 // Check that the hostname is reasonable
216 for(char *p = hostname; *p; p++) {
217 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
219 // If not, forget it.
228 // fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
235 fprintf(stderr, "Please enter your host's external address or hostname");
237 fprintf(stderr, " [%s]", hostname);
238 fprintf(stderr, ": ");
240 if(!fgets(line, sizeof line, stdin)) {
241 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
253 for(char *p = line; *p; p++) {
254 if(isalnum(*p) || *p == '-' || *p == '.')
256 fprintf(stderr, "Invalid address or hostname.\n");
261 hostname = xstrdup(line);
265 FILE *f = fopen(filename, "a");
267 fprintf(f, "\nAddress = %s\n", hostname);
270 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
276 if(strchr(hostname, ':'))
277 xasprintf(&hostport, "[%s]:%s", hostname, port);
279 xasprintf(&hostport, "%s:%s", hostname, port);
281 if(strchr(hostname, ':'))
282 xasprintf(&hostport, "[%s]", hostname);
284 hostport = xstrdup(hostname);
292 static char *get_line(const char **data) {
301 static char line[1024];
302 const char *end = strchr(*data, '\n');
303 size_t len = end ? end - *data : strlen(*data);
304 if(len >= sizeof line) {
305 fprintf(stderr, "Maximum line length exceeded!\n");
308 if(len && !isprint(**data))
311 memcpy(line, *data, len);
322 static char *get_value(const char *data, const char *var) {
323 char *line = get_line(&data);
327 char *sep = line + strcspn(line, " \t=");
328 char *val = sep + strspn(sep, " \t");
330 val += 1 + strspn(val + 1, " \t");
332 if(strcasecmp(line, var))
336 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
337 mode_t mask = umask(0);
340 FILE *f = fopen(filename, mode);
342 if((perms & 0444) && f)
343 fchmod(fileno(f), perms);
349 static bool finalize_join(meshlink_handle_t *mesh) {
350 char *name = xstrdup(get_value(mesh->data, "Name"));
352 fprintf(stderr, "No Name found in invitation!\n");
356 if(!check_id(name)) {
357 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
361 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
362 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
366 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
367 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
371 FILE *f = fopen(mesh->meshlink_conf, "w");
373 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
377 fprintf(f, "Name = %s\n", name);
379 char filename[PATH_MAX];
380 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, name);
381 FILE *fh = fopen(filename, "w");
383 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
387 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
388 // Other chunks go unfiltered to their respective host config files
389 const char *p = mesh->data;
392 while((l = get_line(&p))) {
397 // Split line into variable and value
398 int len = strcspn(l, "\t =");
400 value += strspn(value, "\t ");
403 value += strspn(value, "\t ");
408 if(!strcasecmp(l, "Name"))
409 if(strcmp(value, name))
413 else if(!strcasecmp(l, "NetName"))
416 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
419 for(i = 0; variables[i].name; i++) {
420 if(strcasecmp(l, variables[i].name))
426 // Ignore unknown and unsafe variables
428 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
430 } else if(!(variables[i].type & VAR_SAFE)) {
431 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
435 // Copy the safe variable to the right config file
436 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
441 while(l && !strcasecmp(l, "Name")) {
442 if(!check_id(value)) {
443 fprintf(stderr, "Invalid Name found in invitation.\n");
447 if(!strcmp(value, name)) {
448 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
452 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, value);
453 f = fopen(filename, "w");
456 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
460 while((l = get_line(&p))) {
461 if(!strcmp(l, "#---------------------------------------------------------------#"))
463 int len = strcspn(l, "\t =");
464 if(len == 4 && !strncasecmp(l, "Name", 4)) {
466 value += strspn(value, "\t ");
469 value += strspn(value, "\t ");
482 // Generate our key and send a copy to the server
483 ecdsa_t *key = ecdsa_generate();
487 char *b64key = ecdsa_get_base64_public_key(key);
491 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
492 f = fopenmask(filename, "w", 0600);
494 if(!ecdsa_write_pem_private_key(key, f)) {
495 fprintf(stderr, "Error writing private key!\n");
503 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
505 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
512 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
517 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
518 meshlink_handle_t* mesh = handle;
520 int result = send(mesh->sock, data, len, 0);
521 if(result == -1 && errno == EINTR)
531 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
532 meshlink_handle_t* mesh = handle;
534 case SPTPS_HANDSHAKE:
535 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
538 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
539 memcpy(mesh->data + mesh->thedatalen, msg, len);
540 mesh->thedatalen += len;
541 mesh->data[mesh->thedatalen] = 0;
545 return finalize_join(mesh);
548 fprintf(stderr, "Invitation succesfully accepted.\n");
549 shutdown(mesh->sock, SHUT_RDWR);
550 mesh->success = true;
560 static bool recvline(meshlink_handle_t* mesh, size_t len) {
561 char *newline = NULL;
566 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
567 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
568 if(result == -1 && errno == EINTR)
572 mesh->blen += result;
575 if(newline - mesh->buffer >= len)
578 len = newline - mesh->buffer;
580 memcpy(mesh->line, mesh->buffer, len);
582 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
583 mesh->blen -= len + 1;
587 static bool sendline(int fd, char *format, ...) {
588 static char buffer[4096];
593 va_start(ap, format);
594 blen = vsnprintf(buffer, sizeof buffer, format, ap);
597 if(blen < 1 || blen >= sizeof buffer)
604 int result = send(fd, p, blen, MSG_NOSIGNAL);
605 if(result == -1 && errno == EINTR)
615 int rstrip(char *value) {
616 int len = strlen(value);
617 while(len && strchr("\t\r\n ", value[len - 1]))
623 static const char *errstr[] = {
624 [MESHLINK_OK] = "No error",
625 [MESHLINK_ENOMEM] = "Out of memory",
626 [MESHLINK_ENOENT] = "No such node",
629 const char *meshlink_strerror(meshlink_errno_t errno) {
630 return errstr[errno];
633 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
636 char pubname[PATH_MAX], privname[PATH_MAX];
638 fprintf(stderr, "Generating ECDSA keypair:\n");
640 if(!(key = ecdsa_generate())) {
641 fprintf(stderr, "Error during key generation!\n");
644 fprintf(stderr, "Done.\n");
646 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
647 f = fopen(privname, "w");
653 fchmod(fileno(f), 0600);
656 if(!ecdsa_write_pem_private_key(key, f)) {
657 fprintf(stderr, "Error writing private key!\n");
666 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
667 f = fopen(pubname, "a");
672 char *pubkey = ecdsa_get_base64_public_key(key);
673 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
682 static bool try_bind(int port) {
683 struct addrinfo *ai = NULL;
684 struct addrinfo hint = {
685 .ai_flags = AI_PASSIVE,
686 .ai_family = AF_UNSPEC,
687 .ai_socktype = SOCK_STREAM,
688 .ai_protocol = IPPROTO_TCP,
692 snprintf(portstr, sizeof portstr, "%d", port);
694 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
698 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
701 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
711 int check_port(meshlink_handle_t *mesh) {
715 fprintf(stderr, "Warning: could not bind to port 655.\n");
717 for(int i = 0; i < 100; i++) {
718 int port = 0x1000 + (rand() & 0x7fff);
720 char filename[PATH_MAX];
721 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
722 FILE *f = fopen(filename, "a");
724 fprintf(stderr, "Please change MeshLink's Port manually.\n");
728 fprintf(f, "Port = %d\n", port);
730 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
735 fprintf(stderr, "Please change MeshLink's Port manually.\n");
739 static bool meshlink_setup(meshlink_handle_t *mesh) {
741 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
742 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
746 snprintf(mesh->hosts_dir, sizeof mesh->hosts_dir, "%s" SLASH "hosts", mesh->confbase);
748 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
749 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
753 snprintf(mesh->meshlink_conf, sizeof mesh->meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
755 if(!access(mesh->meshlink_conf, F_OK)) {
756 fprintf(stderr, "Configuration file %s already exists!\n", mesh->meshlink_conf);
760 FILE *f = fopen(mesh->meshlink_conf, "w");
762 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
766 fprintf(f, "Name = %s\n", mesh->name);
769 if(!ecdsa_keygen(mesh))
777 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
778 // Validate arguments provided by the application
780 if(!confbase || !*confbase) {
781 fprintf(stderr, "No confbase given!\n");
785 if(!name || !*name) {
786 fprintf(stderr, "No name given!\n");
790 if(!check_id(name)) {
791 fprintf(stderr, "Invalid name given!\n");
795 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
796 mesh->confbase = xstrdup(confbase);
797 mesh->name = xstrdup(name);
798 event_loop_init(&mesh->loop);
799 mesh->loop.data = mesh;
801 // TODO: should be set by a function.
802 mesh->debug_level = 5;
804 // Check whether meshlink.conf already exists
806 char filename[PATH_MAX];
807 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
809 if(access(filename, R_OK)) {
810 if(errno == ENOENT) {
812 meshlink_setup(mesh);
814 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
815 return meshlink_close(mesh), NULL;
819 // Read the configuration
821 init_configuration(&mesh->config);
823 if(!read_server_config(mesh))
824 return meshlink_close(mesh), NULL;
826 // Setup up everything
827 // TODO: we should not open listening sockets yet
829 if(!setup_network(mesh))
830 return meshlink_close(mesh), NULL;
835 void *meshlink_main_loop(void *arg) {
836 meshlink_handle_t *mesh = arg;
838 try_outgoing_connections(mesh);
845 bool meshlink_start(meshlink_handle_t *mesh) {
846 // TODO: open listening sockets first
848 // Start the main thread
850 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
851 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
852 memset(&mesh->thread, 0, sizeof mesh->thread);
859 void meshlink_stop(meshlink_handle_t *mesh) {
860 // TODO: close the listening sockets to signal the main thread to shut down
862 // Wait for the main thread to finish
864 pthread_join(mesh->thread, NULL);
867 void meshlink_close(meshlink_handle_t *mesh) {
868 // Close and free all resources used.
870 close_network_connections(mesh);
872 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
874 exit_configuration(&mesh->config);
875 event_loop_exit(&mesh->loop);
878 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
879 mesh->receive_cb = cb;
882 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
883 mesh->node_status_cb = cb;
886 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
888 mesh->log_level = level;
891 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
893 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
894 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
899 packet.probe = false;
900 memset(hdr, 0, sizeof *hdr);
901 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
902 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
904 packet.len = sizeof *hdr + len;
905 memcpy(packet.data + sizeof *hdr, data, len);
907 mesh->self->in_packets++;
908 mesh->self->in_bytes += packet.len;
909 route(mesh, mesh->self, &packet);
913 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
914 return (meshlink_node_t *)lookup_node(mesh, name);
918 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
922 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
926 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
930 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
931 // Check validity of the new node's name
932 if(!check_id(name)) {
933 fprintf(stderr, "Invalid name for node.\n");
937 // Ensure no host configuration file with that name exists
938 char filename [PATH_MAX];
939 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
940 if(!access(filename, F_OK)) {
941 fprintf(stderr, "A host config file for %s already exists!\n", name);
945 // If a daemon is running, ensure no other nodes know about this name
947 //TODO: original tinc code connects to tincd cli and makes this check. How we want to implement this here ?
948 //bool found = false;
949 //if(connect_tincd(false)) {
950 // sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
952 // while(recvline(fd, line, sizeof line)) {
955 // if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
957 // if(!strcmp(node, name))
962 // fprintf(stderr, "A node with name %s is already known!\n", name);
969 snprintf(filename,PATH_MAX, "%s" SLASH "invitations", mesh->confbase);
970 if(mkdir(filename, 0700) && errno != EEXIST) {
971 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
975 // Count the number of valid invitations, clean up old ones
976 DIR *dir = opendir(filename);
978 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
985 time_t deadline = time(NULL) - 604800; // 1 week in the past
987 while((ent = readdir(dir))) {
988 if(strlen(ent->d_name) != 24)
990 char invname[PATH_MAX];
992 snprintf(invname,PATH_MAX, "%s" SLASH "%s", filename, ent->d_name);
993 if(!stat(invname, &st)) {
994 if(deadline < st.st_mtime)
999 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1005 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1013 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1015 // Remove the key if there are no outstanding invitations.
1019 // Create a new key if necessary.
1020 FILE *f = fopen(filename, "r");
1022 if(errno != ENOENT) {
1023 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1027 key = ecdsa_generate();
1029 fprintf(stderr, "Could not generate a new key!\n");
1032 f = fopen(filename, "w");
1034 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1037 chmod(filename, 0600);
1038 ecdsa_write_pem_private_key(key, f);
1040 //TODO: handle this in meshlink
1041 //if(connect_tincd(false))
1042 // sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1044 key = ecdsa_read_pem_private_key(f);
1047 fprintf(stderr, "Could not read private key from %s\n", filename);
1053 // Create a hash of the key.
1054 char *fingerprint = ecdsa_get_base64_public_key(key);
1055 sha512(fingerprint, strlen(fingerprint), hash);
1056 b64encode_urlsafe(hash, hash, 18);
1058 // Create a random cookie for this invitation.
1060 randomize(cookie, 18);
1062 // Create a filename that doesn't reveal the cookie itself
1063 char buf[18 + strlen(fingerprint)];
1064 char cookiehash[64];
1065 memcpy(buf, cookie, 18);
1066 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1067 sha512(buf, sizeof buf, cookiehash);
1068 b64encode_urlsafe(cookiehash, cookiehash, 18);
1070 b64encode_urlsafe(cookie, cookie, 18);
1072 // Create a file containing the details of the invitation.
1073 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1074 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1076 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1079 f = fdopen(ifd, "w");
1083 // Get the local address
1084 char *address = get_my_hostname(mesh);
1086 // Fill in the details.
1087 fprintf(f, "Name = %s\n", name);
1089 // fprintf(f, "NetName = %s\n", netname);
1090 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1092 // Copy Broadcast and Mode
1093 FILE *tc = fopen(mesh->meshlink_conf, "r");
1096 while(fgets(buf, sizeof buf, tc)) {
1097 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1098 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1100 // Make sure there is a newline character.
1101 if(!strchr(buf, '\n'))
1108 fprintf(f, "#---------------------------------------------------------------#\n");
1109 fprintf(f, "Name = %s\n", mesh->self->name);
1111 char filename2[PATH_MAX];
1112 snprintf(filename2,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1113 fcopy(f, filename2);
1116 // Create an URL from the local address, key hash and cookie
1118 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1123 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1126 // Make sure confbase exists and is accessible.
1127 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1128 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1132 if(access(mesh->confbase, R_OK | W_OK | X_OK)) {
1133 fprintf(stderr, "No permission to write in directory %s: %s\n", mesh->confbase, strerror(errno));
1137 // TODO: Either remove or reintroduce netname in meshlink
1138 // If a netname or explicit configuration directory is specified, check for an existing meshlink.conf.
1139 //if((mesh->netname || confbasegiven) && !access(meshlink_conf, F_OK)) {
1140 // fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
1144 char *slash = strchr(invitation, '/');
1150 if(strlen(slash) != 48)
1153 char *address = invitation;
1155 if(*address == '[') {
1157 char *bracket = strchr(address, ']');
1161 if(bracket[1] == ':')
1164 port = strchr(address, ':');
1169 if(!mesh->myport || !*port)
1172 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1175 // Generate a throw-away key for the invitation.
1176 ecdsa_t *key = ecdsa_generate();
1180 char *b64key = ecdsa_get_base64_public_key(key);
1182 // Connect to the meshlink daemon mentioned in the URL.
1183 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1187 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1188 if(mesh->sock <= 0) {
1189 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1193 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1194 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1195 closesocket(mesh->sock);
1199 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1201 // Tell him we have an invitation, and give him our throw-away key.
1202 int len = snprintf(invitation, sizeof invitation, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1203 if(len <= 0 || len >= sizeof invitation)
1206 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1207 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1208 closesocket(mesh->sock);
1212 char hisname[4096] = "";
1213 int code, hismajor, hisminor = 0;
1215 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) {
1216 fprintf(stderr, "Cannot read greeting from peer\n");
1217 closesocket(mesh->sock);
1221 // Check if the hash of the key he gave us matches the hash in the URL.
1222 char *fingerprint = mesh->line + 2;
1224 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
1225 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1228 if(memcmp(hishash, mesh->hash, 18)) {
1229 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1234 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1238 // Start an SPTPS session
1239 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1242 // Feed rest of input buffer to SPTPS
1243 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1246 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1250 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1254 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1258 sptps_stop(&mesh->sptps);
1261 closesocket(mesh->sock);
1263 if(!mesh->success) {
1264 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1271 fprintf(stderr, "Invalid invitation URL.\n");
1275 char *meshlink_export(meshlink_handle_t *mesh) {
1279 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1283 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1286 static void __attribute__((constructor)) meshlink_init(void) {
1290 static void __attribute__((destructor)) meshlink_exit(void) {