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 //TODO: this can go away completely
45 const var_t variables[] = {
46 /* Server configuration */
47 {"AddressFamily", VAR_SERVER},
48 {"AutoConnect", VAR_SERVER | VAR_SAFE},
49 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
50 {"BindToInterface", VAR_SERVER},
51 {"Broadcast", VAR_SERVER | VAR_SAFE},
52 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
53 {"DecrementTTL", VAR_SERVER},
54 {"Device", VAR_SERVER},
55 {"DeviceType", VAR_SERVER},
56 {"DirectOnly", VAR_SERVER},
57 {"ECDSAPrivateKeyFile", VAR_SERVER},
58 {"ExperimentalProtocol", VAR_SERVER},
59 {"Forwarding", VAR_SERVER},
60 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
61 {"Hostnames", VAR_SERVER},
62 {"IffOneQueue", VAR_SERVER},
63 {"Interface", VAR_SERVER},
64 {"KeyExpire", VAR_SERVER},
65 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
66 {"LocalDiscovery", VAR_SERVER},
67 {"MACExpire", VAR_SERVER},
68 {"MaxConnectionBurst", VAR_SERVER},
69 {"MaxOutputBufferSize", VAR_SERVER},
70 {"MaxTimeout", VAR_SERVER},
71 {"Mode", VAR_SERVER | VAR_SAFE},
73 {"PingInterval", VAR_SERVER},
74 {"PingTimeout", VAR_SERVER},
75 {"PriorityInheritance", VAR_SERVER},
76 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
77 {"PrivateKeyFile", VAR_SERVER},
78 {"ProcessPriority", VAR_SERVER},
79 {"Proxy", VAR_SERVER},
80 {"ReplayWindow", VAR_SERVER},
81 {"ScriptsExtension", VAR_SERVER},
82 {"ScriptsInterpreter", VAR_SERVER},
83 {"StrictSubnets", VAR_SERVER},
84 {"TunnelServer", VAR_SERVER},
85 {"VDEGroup", VAR_SERVER},
86 {"VDEPort", VAR_SERVER},
87 /* Host configuration */
88 {"Address", VAR_HOST | VAR_MULTIPLE},
89 {"Cipher", VAR_SERVER | VAR_HOST},
90 {"ClampMSS", VAR_SERVER | VAR_HOST},
91 {"Compression", VAR_SERVER | VAR_HOST},
92 {"Digest", VAR_SERVER | VAR_HOST},
93 {"ECDSAPublicKey", VAR_HOST},
94 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
95 {"IndirectData", VAR_SERVER | VAR_HOST},
96 {"MACLength", VAR_SERVER | VAR_HOST},
97 {"PMTU", VAR_SERVER | VAR_HOST},
98 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
100 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
101 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
102 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
103 {"TCPOnly", VAR_SERVER | VAR_HOST},
104 {"Weight", VAR_HOST | VAR_SAFE},
108 static bool fcopy(FILE *out, const char *filename) {
109 FILE *in = fopen(filename, "r");
111 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
117 while((len = fread(buf, 1, sizeof buf, in)))
118 fwrite(buf, len, 1, out);
123 static int rstrip(char *value) {
124 int len = strlen(value);
125 while(len && strchr("\t\r\n ", value[len - 1]))
130 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
132 if(!filename || (*hostname && *port))
135 FILE *f = fopen(filename, "r");
139 while(fgets(line, sizeof line, f)) {
143 p += strcspn(p, "\t =");
146 q = p + strspn(p, "\t ");
148 q += 1 + strspn(q + 1, "\t ");
150 p = q + strcspn(q, "\t ");
153 p += strspn(p, "\t ");
154 p[strcspn(p, "\t ")] = 0;
156 if(!*port && !strcasecmp(line, "Port")) {
158 } else if(!*hostname && !strcasecmp(line, "Address")) {
159 *hostname = xstrdup(q);
166 if(*hostname && *port)
172 static char *get_my_hostname(meshlink_handle_t* mesh) {
173 char *hostname = NULL;
175 char *hostport = NULL;
176 char *name = mesh->self->name;
177 char filename[PATH_MAX] = "";
181 // Use first Address statement in own host config file
182 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
183 scan_for_hostname(filename, &hostname, &port);
188 // If that doesn't work, guess externally visible hostname
189 fprintf(stderr, "Trying to discover externally visible hostname...\n");
190 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
191 struct addrinfo *aip = ai;
192 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
195 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
197 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
203 send(s, request, sizeof request - 1, 0);
204 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
207 if(line[len - 1] == '\n')
209 char *p = strrchr(line, '\n');
211 hostname = xstrdup(p + 1);
224 // Check that the hostname is reasonable
226 for(char *p = hostname; *p; p++) {
227 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
229 // If not, forget it.
238 // fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
245 fprintf(stderr, "Please enter your host's external address or hostname");
247 fprintf(stderr, " [%s]", hostname);
248 fprintf(stderr, ": ");
250 if(!fgets(line, sizeof line, stdin)) {
251 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
263 for(char *p = line; *p; p++) {
264 if(isalnum(*p) || *p == '-' || *p == '.')
266 fprintf(stderr, "Invalid address or hostname.\n");
271 hostname = xstrdup(line);
274 f = fopen(filename, "a");
276 fprintf(f, "\nAddress = %s\n", hostname);
279 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
284 if(strchr(hostname, ':'))
285 xasprintf(&hostport, "[%s]:%s", hostname, port);
287 xasprintf(&hostport, "%s:%s", hostname, port);
289 if(strchr(hostname, ':'))
290 xasprintf(&hostport, "[%s]", hostname);
292 hostport = xstrdup(hostname);
300 static char *get_line(const char **data) {
309 static char line[1024];
310 const char *end = strchr(*data, '\n');
311 size_t len = end ? end - *data : strlen(*data);
312 if(len >= sizeof line) {
313 fprintf(stderr, "Maximum line length exceeded!\n");
316 if(len && !isprint(**data))
319 memcpy(line, *data, len);
330 static char *get_value(const char *data, const char *var) {
331 char *line = get_line(&data);
335 char *sep = line + strcspn(line, " \t=");
336 char *val = sep + strspn(sep, " \t");
338 val += 1 + strspn(val + 1, " \t");
340 if(strcasecmp(line, var))
344 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
345 mode_t mask = umask(0);
348 FILE *f = fopen(filename, mode);
350 if((perms & 0444) && f)
351 fchmod(fileno(f), perms);
357 static bool try_bind(int port) {
358 struct addrinfo *ai = NULL;
359 struct addrinfo hint = {
360 .ai_flags = AI_PASSIVE,
361 .ai_family = AF_UNSPEC,
362 .ai_socktype = SOCK_STREAM,
363 .ai_protocol = IPPROTO_TCP,
367 snprintf(portstr, sizeof portstr, "%d", port);
369 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
373 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
376 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
386 static int check_port(meshlink_handle_t *mesh) {
390 fprintf(stderr, "Warning: could not bind to port 655.\n");
392 for(int i = 0; i < 100; i++) {
393 int port = 0x1000 + (rand() & 0x7fff);
395 char filename[PATH_MAX];
396 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
397 FILE *f = fopen(filename, "a");
399 fprintf(stderr, "Please change MeshLink's Port manually.\n");
403 fprintf(f, "Port = %d\n", port);
405 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
410 fprintf(stderr, "Please change MeshLink's Port manually.\n");
414 static bool finalize_join(meshlink_handle_t *mesh) {
415 char *name = xstrdup(get_value(mesh->data, "Name"));
417 fprintf(stderr, "No Name found in invitation!\n");
421 if(!check_id(name)) {
422 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
426 char filename[PATH_MAX];
427 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
429 FILE *f = fopen(filename, "w");
431 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
435 fprintf(f, "Name = %s\n", name);
437 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
438 FILE *fh = fopen(filename, "w");
440 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
444 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
445 // Other chunks go unfiltered to their respective host config files
446 const char *p = mesh->data;
449 while((l = get_line(&p))) {
454 // Split line into variable and value
455 int len = strcspn(l, "\t =");
457 value += strspn(value, "\t ");
460 value += strspn(value, "\t ");
465 if(!strcasecmp(l, "Name"))
466 if(strcmp(value, name))
470 else if(!strcasecmp(l, "NetName"))
473 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
476 for(i = 0; variables[i].name; i++) {
477 if(strcasecmp(l, variables[i].name))
483 // Ignore unknown and unsafe variables
485 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
487 } else if(!(variables[i].type & VAR_SAFE)) {
488 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
492 // Copy the safe variable to the right config file
493 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
498 while(l && !strcasecmp(l, "Name")) {
499 if(!check_id(value)) {
500 fprintf(stderr, "Invalid Name found in invitation.\n");
504 if(!strcmp(value, name)) {
505 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
509 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
510 f = fopen(filename, "w");
513 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
517 while((l = get_line(&p))) {
518 if(!strcmp(l, "#---------------------------------------------------------------#"))
520 int len = strcspn(l, "\t =");
521 if(len == 4 && !strncasecmp(l, "Name", 4)) {
523 value += strspn(value, "\t ");
526 value += strspn(value, "\t ");
539 // Generate our key and send a copy to the server
540 ecdsa_t *key = ecdsa_generate();
544 char *b64key = ecdsa_get_base64_public_key(key);
548 snprintf(filename, sizeof filename, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
549 f = fopenmask(filename, "w", 0600);
551 if(!ecdsa_write_pem_private_key(key, f)) {
552 fprintf(stderr, "Error writing private key!\n");
560 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
561 fprintf(fh, "Port = %s\n", mesh->myport);
565 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
570 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
575 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
576 meshlink_handle_t* mesh = handle;
578 int result = send(mesh->sock, data, len, 0);
579 if(result == -1 && errno == EINTR)
589 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
590 meshlink_handle_t* mesh = handle;
592 case SPTPS_HANDSHAKE:
593 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
596 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
597 memcpy(mesh->data + mesh->thedatalen, msg, len);
598 mesh->thedatalen += len;
599 mesh->data[mesh->thedatalen] = 0;
603 return finalize_join(mesh);
606 fprintf(stderr, "Invitation succesfully accepted.\n");
607 shutdown(mesh->sock, SHUT_RDWR);
608 mesh->success = true;
618 static bool recvline(meshlink_handle_t* mesh, size_t len) {
619 char *newline = NULL;
624 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
625 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
626 if(result == -1 && errno == EINTR)
630 mesh->blen += result;
633 if(newline - mesh->buffer >= len)
636 len = newline - mesh->buffer;
638 memcpy(mesh->line, mesh->buffer, len);
640 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
641 mesh->blen -= len + 1;
645 static bool sendline(int fd, char *format, ...) {
646 static char buffer[4096];
651 va_start(ap, format);
652 blen = vsnprintf(buffer, sizeof buffer, format, ap);
655 if(blen < 1 || blen >= sizeof buffer)
662 int result = send(fd, p, blen, MSG_NOSIGNAL);
663 if(result == -1 && errno == EINTR)
674 static const char *errstr[] = {
675 [MESHLINK_OK] = "No error",
676 [MESHLINK_ENOMEM] = "Out of memory",
677 [MESHLINK_ENOENT] = "No such node",
680 const char *meshlink_strerror(meshlink_errno_t errno) {
681 return errstr[errno];
684 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
687 char pubname[PATH_MAX], privname[PATH_MAX];
689 fprintf(stderr, "Generating ECDSA keypair:\n");
691 if(!(key = ecdsa_generate())) {
692 fprintf(stderr, "Error during key generation!\n");
695 fprintf(stderr, "Done.\n");
697 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
698 f = fopen(privname, "w");
704 fchmod(fileno(f), 0600);
707 if(!ecdsa_write_pem_private_key(key, f)) {
708 fprintf(stderr, "Error writing private key!\n");
717 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
718 f = fopen(pubname, "a");
723 char *pubkey = ecdsa_get_base64_public_key(key);
724 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
733 static bool meshlink_setup(meshlink_handle_t *mesh) {
734 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
735 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
739 char filename[PATH_MAX];
740 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
742 if(mkdir(filename, 0777) && errno != EEXIST) {
743 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
747 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
749 if(!access(filename, F_OK)) {
750 fprintf(stderr, "Configuration file %s already exists!\n", filename);
754 FILE *f = fopen(filename, "w");
756 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
760 fprintf(f, "Name = %s\n", mesh->name);
763 if(!ecdsa_keygen(mesh))
771 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
772 // Validate arguments provided by the application
774 if(!confbase || !*confbase) {
775 fprintf(stderr, "No confbase given!\n");
779 if(!name || !*name) {
780 fprintf(stderr, "No name given!\n");
784 if(!check_id(name)) {
785 fprintf(stderr, "Invalid name given!\n");
789 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
790 mesh->confbase = xstrdup(confbase);
791 mesh->name = xstrdup(name);
792 event_loop_init(&mesh->loop);
793 mesh->loop.data = mesh;
795 // TODO: should be set by a function.
796 mesh->debug_level = 5;
798 // Check whether meshlink.conf already exists
800 char filename[PATH_MAX];
801 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
803 if(access(filename, R_OK)) {
804 if(errno == ENOENT) {
806 meshlink_setup(mesh);
808 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
809 return meshlink_close(mesh), NULL;
813 // Read the configuration
815 init_configuration(&mesh->config);
817 if(!read_server_config(mesh))
818 return meshlink_close(mesh), NULL;
820 // Setup up everything
821 // TODO: we should not open listening sockets yet
823 if(!setup_network(mesh))
824 return meshlink_close(mesh), NULL;
829 void *meshlink_main_loop(void *arg) {
830 meshlink_handle_t *mesh = arg;
832 try_outgoing_connections(mesh);
839 bool meshlink_start(meshlink_handle_t *mesh) {
840 // TODO: open listening sockets first
842 // Start the main thread
844 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
845 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
846 memset(&mesh->thread, 0, sizeof mesh->thread);
853 void meshlink_stop(meshlink_handle_t *mesh) {
854 // TODO: close the listening sockets to signal the main thread to shut down
856 // Wait for the main thread to finish
858 pthread_join(mesh->thread, NULL);
861 void meshlink_close(meshlink_handle_t *mesh) {
862 // Close and free all resources used.
864 close_network_connections(mesh);
866 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
868 exit_configuration(&mesh->config);
869 event_loop_exit(&mesh->loop);
872 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
873 mesh->receive_cb = cb;
876 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
877 mesh->node_status_cb = cb;
880 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
882 mesh->log_level = level;
885 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
887 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
888 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
893 packet.probe = false;
894 memset(hdr, 0, sizeof *hdr);
895 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
896 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
898 packet.len = sizeof *hdr + len;
899 memcpy(packet.data + sizeof *hdr, data, len);
901 mesh->self->in_packets++;
902 mesh->self->in_bytes += packet.len;
903 route(mesh, mesh->self, &packet);
907 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
908 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
911 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
915 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
919 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
923 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
924 char filename[PATH_MAX];
926 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
927 if(mkdir(filename, 0700) && errno != EEXIST) {
928 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
932 // Count the number of valid invitations, clean up old ones
933 DIR *dir = opendir(filename);
935 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
942 time_t deadline = time(NULL) - 604800; // 1 week in the past
944 while((ent = readdir(dir))) {
945 if(strlen(ent->d_name) != 24)
947 char invname[PATH_MAX];
949 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
950 if(!stat(invname, &st)) {
951 if(mesh->invitation_key && deadline < st.st_mtime)
956 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
962 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
969 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
971 // Remove the key if there are no outstanding invitations.
974 if(mesh->invitation_key) {
975 ecdsa_free(mesh->invitation_key);
976 mesh->invitation_key = NULL;
980 if(mesh->invitation_key)
983 // Create a new key if necessary.
984 FILE *f = fopen(filename, "r");
986 if(errno != ENOENT) {
987 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
991 mesh->invitation_key = ecdsa_generate();
992 if(!mesh->invitation_key) {
993 fprintf(stderr, "Could not generate a new key!\n");
996 f = fopen(filename, "w");
998 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1001 chmod(filename, 0600);
1002 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1005 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1007 if(!mesh->invitation_key)
1008 fprintf(stderr, "Could not read private key from %s\n", filename);
1011 return mesh->invitation_key;
1014 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1015 // Check validity of the new node's name
1016 if(!check_id(name)) {
1017 fprintf(stderr, "Invalid name for node.\n");
1021 // Ensure no host configuration file with that name exists
1022 char filename[PATH_MAX];
1023 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1024 if(!access(filename, F_OK)) {
1025 fprintf(stderr, "A host config file for %s already exists!\n", name);
1029 // Ensure no other nodes know about this name
1030 if(meshlink_get_node(mesh, name)) {
1031 fprintf(stderr, "A node with name %s is already known!\n", name);
1035 if(!refresh_invitation_key(mesh))
1040 // Create a hash of the key.
1041 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1042 sha512(fingerprint, strlen(fingerprint), hash);
1043 b64encode_urlsafe(hash, hash, 18);
1045 // Create a random cookie for this invitation.
1047 randomize(cookie, 18);
1049 // Create a filename that doesn't reveal the cookie itself
1050 char buf[18 + strlen(fingerprint)];
1051 char cookiehash[64];
1052 memcpy(buf, cookie, 18);
1053 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1054 sha512(buf, sizeof buf, cookiehash);
1055 b64encode_urlsafe(cookiehash, cookiehash, 18);
1057 b64encode_urlsafe(cookie, cookie, 18);
1059 // Create a file containing the details of the invitation.
1060 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1061 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1063 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1066 FILE *f = fdopen(ifd, "w");
1070 // Get the local address
1071 char *address = get_my_hostname(mesh);
1073 // Fill in the details.
1074 fprintf(f, "Name = %s\n", name);
1076 // fprintf(f, "NetName = %s\n", netname);
1077 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1079 // Copy Broadcast and Mode
1080 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1081 FILE *tc = fopen(filename, "r");
1084 while(fgets(buf, sizeof buf, tc)) {
1085 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1086 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1088 // Make sure there is a newline character.
1089 if(!strchr(buf, '\n'))
1095 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1099 fprintf(f, "#---------------------------------------------------------------#\n");
1100 fprintf(f, "Name = %s\n", mesh->self->name);
1102 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1106 // Create an URL from the local address, key hash and cookie
1108 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1113 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1114 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1115 char copy[strlen(invitation) + 1];
1116 strcpy(copy, invitation);
1118 // Split the invitation URL into hostname, port, key hash and cookie.
1120 char *slash = strchr(copy, '/');
1126 if(strlen(slash) != 48)
1129 char *address = copy;
1131 if(*address == '[') {
1133 char *bracket = strchr(address, ']');
1137 if(bracket[1] == ':')
1140 port = strchr(address, ':');
1148 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1151 // Generate a throw-away key for the invitation.
1152 ecdsa_t *key = ecdsa_generate();
1156 char *b64key = ecdsa_get_base64_public_key(key);
1158 // Connect to the meshlink daemon mentioned in the URL.
1159 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1163 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1164 if(mesh->sock <= 0) {
1165 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1169 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1170 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1171 closesocket(mesh->sock);
1175 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1177 // Tell him we have an invitation, and give him our throw-away key.
1181 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1182 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1183 closesocket(mesh->sock);
1187 char hisname[4096] = "";
1188 int code, hismajor, hisminor = 0;
1190 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) {
1191 fprintf(stderr, "Cannot read greeting from peer\n");
1192 closesocket(mesh->sock);
1196 // Check if the hash of the key he gave us matches the hash in the URL.
1197 char *fingerprint = mesh->line + 2;
1199 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1200 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1203 if(memcmp(hishash, mesh->hash, 18)) {
1204 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1209 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1213 // Start an SPTPS session
1214 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1217 // Feed rest of input buffer to SPTPS
1218 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1223 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1227 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1231 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1235 sptps_stop(&mesh->sptps);
1238 closesocket(mesh->sock);
1240 if(!mesh->success) {
1241 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1248 fprintf(stderr, "Invalid invitation URL.\n");
1252 char *meshlink_export(meshlink_handle_t *mesh) {
1256 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1260 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1263 static void __attribute__((constructor)) meshlink_init(void) {
1267 static void __attribute__((destructor)) meshlink_exit(void) {