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,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
183 scan_for_hostname(filename, &hostname, &port);
184 scan_for_hostname(mesh->meshlink_conf, &hostname, &port);
189 // If that doesn't work, guess externally visible hostname
190 fprintf(stderr, "Trying to discover externally visible hostname...\n");
191 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
192 struct addrinfo *aip = ai;
193 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
196 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
198 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
204 send(s, request, sizeof request - 1, 0);
205 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
208 if(line[len - 1] == '\n')
210 char *p = strrchr(line, '\n');
212 hostname = xstrdup(p + 1);
225 // Check that the hostname is reasonable
227 for(char *p = hostname; *p; p++) {
228 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
230 // If not, forget it.
239 // fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
246 fprintf(stderr, "Please enter your host's external address or hostname");
248 fprintf(stderr, " [%s]", hostname);
249 fprintf(stderr, ": ");
251 if(!fgets(line, sizeof line, stdin)) {
252 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
264 for(char *p = line; *p; p++) {
265 if(isalnum(*p) || *p == '-' || *p == '.')
267 fprintf(stderr, "Invalid address or hostname.\n");
272 hostname = xstrdup(line);
275 f = fopen(filename, "a");
277 fprintf(f, "\nAddress = %s\n", hostname);
280 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
285 if(strchr(hostname, ':'))
286 xasprintf(&hostport, "[%s]:%s", hostname, port);
288 xasprintf(&hostport, "%s:%s", hostname, port);
290 if(strchr(hostname, ':'))
291 xasprintf(&hostport, "[%s]", hostname);
293 hostport = xstrdup(hostname);
301 static char *get_line(const char **data) {
310 static char line[1024];
311 const char *end = strchr(*data, '\n');
312 size_t len = end ? end - *data : strlen(*data);
313 if(len >= sizeof line) {
314 fprintf(stderr, "Maximum line length exceeded!\n");
317 if(len && !isprint(**data))
320 memcpy(line, *data, len);
331 static char *get_value(const char *data, const char *var) {
332 char *line = get_line(&data);
336 char *sep = line + strcspn(line, " \t=");
337 char *val = sep + strspn(sep, " \t");
339 val += 1 + strspn(val + 1, " \t");
341 if(strcasecmp(line, var))
345 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
346 mode_t mask = umask(0);
349 FILE *f = fopen(filename, mode);
351 if((perms & 0444) && f)
352 fchmod(fileno(f), perms);
358 static bool try_bind(int port) {
359 struct addrinfo *ai = NULL;
360 struct addrinfo hint = {
361 .ai_flags = AI_PASSIVE,
362 .ai_family = AF_UNSPEC,
363 .ai_socktype = SOCK_STREAM,
364 .ai_protocol = IPPROTO_TCP,
368 snprintf(portstr, sizeof portstr, "%d", port);
370 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
374 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
377 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
387 static int check_port(meshlink_handle_t *mesh) {
391 fprintf(stderr, "Warning: could not bind to port 655.\n");
393 for(int i = 0; i < 100; i++) {
394 int port = 0x1000 + (rand() & 0x7fff);
396 char filename[PATH_MAX];
397 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
398 FILE *f = fopen(filename, "a");
400 fprintf(stderr, "Please change MeshLink's Port manually.\n");
404 fprintf(f, "Port = %d\n", port);
406 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
411 fprintf(stderr, "Please change MeshLink's Port manually.\n");
415 static bool finalize_join(meshlink_handle_t *mesh) {
416 char *name = xstrdup(get_value(mesh->data, "Name"));
418 fprintf(stderr, "No Name found in invitation!\n");
422 if(!check_id(name)) {
423 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
427 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
428 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
432 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
433 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
437 FILE *f = fopen(mesh->meshlink_conf, "w");
439 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
443 fprintf(f, "Name = %s\n", name);
445 char filename[PATH_MAX];
446 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, name);
447 FILE *fh = fopen(filename, "w");
449 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
453 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
454 // Other chunks go unfiltered to their respective host config files
455 const char *p = mesh->data;
458 while((l = get_line(&p))) {
463 // Split line into variable and value
464 int len = strcspn(l, "\t =");
466 value += strspn(value, "\t ");
469 value += strspn(value, "\t ");
474 if(!strcasecmp(l, "Name"))
475 if(strcmp(value, name))
479 else if(!strcasecmp(l, "NetName"))
482 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
485 for(i = 0; variables[i].name; i++) {
486 if(strcasecmp(l, variables[i].name))
492 // Ignore unknown and unsafe variables
494 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
496 } else if(!(variables[i].type & VAR_SAFE)) {
497 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
501 // Copy the safe variable to the right config file
502 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
507 while(l && !strcasecmp(l, "Name")) {
508 if(!check_id(value)) {
509 fprintf(stderr, "Invalid Name found in invitation.\n");
513 if(!strcmp(value, name)) {
514 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
518 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, value);
519 f = fopen(filename, "w");
522 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
526 while((l = get_line(&p))) {
527 if(!strcmp(l, "#---------------------------------------------------------------#"))
529 int len = strcspn(l, "\t =");
530 if(len == 4 && !strncasecmp(l, "Name", 4)) {
532 value += strspn(value, "\t ");
535 value += strspn(value, "\t ");
548 // Generate our key and send a copy to the server
549 ecdsa_t *key = ecdsa_generate();
553 char *b64key = ecdsa_get_base64_public_key(key);
557 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
558 f = fopenmask(filename, "w", 0600);
560 if(!ecdsa_write_pem_private_key(key, f)) {
561 fprintf(stderr, "Error writing private key!\n");
569 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
571 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
578 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
583 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
584 meshlink_handle_t* mesh = handle;
586 int result = send(mesh->sock, data, len, 0);
587 if(result == -1 && errno == EINTR)
597 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
598 meshlink_handle_t* mesh = handle;
600 case SPTPS_HANDSHAKE:
601 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
604 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
605 memcpy(mesh->data + mesh->thedatalen, msg, len);
606 mesh->thedatalen += len;
607 mesh->data[mesh->thedatalen] = 0;
611 return finalize_join(mesh);
614 fprintf(stderr, "Invitation succesfully accepted.\n");
615 shutdown(mesh->sock, SHUT_RDWR);
616 mesh->success = true;
626 static bool recvline(meshlink_handle_t* mesh, size_t len) {
627 char *newline = NULL;
632 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
633 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
634 if(result == -1 && errno == EINTR)
638 mesh->blen += result;
641 if(newline - mesh->buffer >= len)
644 len = newline - mesh->buffer;
646 memcpy(mesh->line, mesh->buffer, len);
648 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
649 mesh->blen -= len + 1;
653 static bool sendline(int fd, char *format, ...) {
654 static char buffer[4096];
659 va_start(ap, format);
660 blen = vsnprintf(buffer, sizeof buffer, format, ap);
663 if(blen < 1 || blen >= sizeof buffer)
670 int result = send(fd, p, blen, MSG_NOSIGNAL);
671 if(result == -1 && errno == EINTR)
682 static const char *errstr[] = {
683 [MESHLINK_OK] = "No error",
684 [MESHLINK_ENOMEM] = "Out of memory",
685 [MESHLINK_ENOENT] = "No such node",
688 const char *meshlink_strerror(meshlink_errno_t errno) {
689 return errstr[errno];
692 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
695 char pubname[PATH_MAX], privname[PATH_MAX];
697 fprintf(stderr, "Generating ECDSA keypair:\n");
699 if(!(key = ecdsa_generate())) {
700 fprintf(stderr, "Error during key generation!\n");
703 fprintf(stderr, "Done.\n");
705 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
706 f = fopen(privname, "w");
712 fchmod(fileno(f), 0600);
715 if(!ecdsa_write_pem_private_key(key, f)) {
716 fprintf(stderr, "Error writing private key!\n");
725 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
726 f = fopen(pubname, "a");
731 char *pubkey = ecdsa_get_base64_public_key(key);
732 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
741 static bool meshlink_setup(meshlink_handle_t *mesh) {
743 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
744 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
748 snprintf(mesh->hosts_dir, sizeof mesh->hosts_dir, "%s" SLASH "hosts", mesh->confbase);
750 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
751 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
755 snprintf(mesh->meshlink_conf, sizeof mesh->meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
757 if(!access(mesh->meshlink_conf, F_OK)) {
758 fprintf(stderr, "Configuration file %s already exists!\n", mesh->meshlink_conf);
762 FILE *f = fopen(mesh->meshlink_conf, "w");
764 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
768 fprintf(f, "Name = %s\n", mesh->name);
771 if(!ecdsa_keygen(mesh))
779 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
780 // Validate arguments provided by the application
782 if(!confbase || !*confbase) {
783 fprintf(stderr, "No confbase given!\n");
787 if(!name || !*name) {
788 fprintf(stderr, "No name given!\n");
792 if(!check_id(name)) {
793 fprintf(stderr, "Invalid name given!\n");
797 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
798 mesh->confbase = xstrdup(confbase);
799 mesh->name = xstrdup(name);
800 event_loop_init(&mesh->loop);
801 mesh->loop.data = mesh;
803 // TODO: should be set by a function.
804 mesh->debug_level = 5;
806 // Check whether meshlink.conf already exists
808 char filename[PATH_MAX];
809 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
811 if(access(filename, R_OK)) {
812 if(errno == ENOENT) {
814 meshlink_setup(mesh);
816 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
817 return meshlink_close(mesh), NULL;
821 // Read the configuration
823 init_configuration(&mesh->config);
825 if(!read_server_config(mesh))
826 return meshlink_close(mesh), NULL;
828 // Setup up everything
829 // TODO: we should not open listening sockets yet
831 if(!setup_network(mesh))
832 return meshlink_close(mesh), NULL;
837 void *meshlink_main_loop(void *arg) {
838 meshlink_handle_t *mesh = arg;
840 try_outgoing_connections(mesh);
847 bool meshlink_start(meshlink_handle_t *mesh) {
848 // TODO: open listening sockets first
850 // Start the main thread
852 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
853 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
854 memset(&mesh->thread, 0, sizeof mesh->thread);
861 void meshlink_stop(meshlink_handle_t *mesh) {
862 // TODO: close the listening sockets to signal the main thread to shut down
864 // Wait for the main thread to finish
866 pthread_join(mesh->thread, NULL);
869 void meshlink_close(meshlink_handle_t *mesh) {
870 // Close and free all resources used.
872 close_network_connections(mesh);
874 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
876 exit_configuration(&mesh->config);
877 event_loop_exit(&mesh->loop);
880 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
881 mesh->receive_cb = cb;
884 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
885 mesh->node_status_cb = cb;
888 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
890 mesh->log_level = level;
893 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
895 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
896 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
901 packet.probe = false;
902 memset(hdr, 0, sizeof *hdr);
903 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
904 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
906 packet.len = sizeof *hdr + len;
907 memcpy(packet.data + sizeof *hdr, data, len);
909 mesh->self->in_packets++;
910 mesh->self->in_bytes += packet.len;
911 route(mesh, mesh->self, &packet);
915 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
916 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
919 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
923 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
927 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
931 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
932 char filename[PATH_MAX];
934 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
935 if(mkdir(filename, 0700) && errno != EEXIST) {
936 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
940 // Count the number of valid invitations, clean up old ones
941 DIR *dir = opendir(filename);
943 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
950 time_t deadline = time(NULL) - 604800; // 1 week in the past
952 while((ent = readdir(dir))) {
953 if(strlen(ent->d_name) != 24)
955 char invname[PATH_MAX];
957 snprintf(invname,PATH_MAX, "%s" SLASH "%s", filename, ent->d_name);
958 if(!stat(invname, &st)) {
959 if(mesh->invitation_key && deadline < st.st_mtime)
964 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
970 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
977 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
979 // Remove the key if there are no outstanding invitations.
982 if(mesh->invitation_key) {
983 ecdsa_free(mesh->invitation_key);
984 mesh->invitation_key = NULL;
988 if(mesh->invitation_key)
991 // Create a new key if necessary.
992 FILE *f = fopen(filename, "r");
994 if(errno != ENOENT) {
995 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
999 mesh->invitation_key = ecdsa_generate();
1000 if(!mesh->invitation_key) {
1001 fprintf(stderr, "Could not generate a new key!\n");
1004 f = fopen(filename, "w");
1006 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1009 chmod(filename, 0600);
1010 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1013 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1015 if(!mesh->invitation_key)
1016 fprintf(stderr, "Could not read private key from %s\n", filename);
1019 return mesh->invitation_key;
1022 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1023 // Check validity of the new node's name
1024 if(!check_id(name)) {
1025 fprintf(stderr, "Invalid name for node.\n");
1029 // Ensure no host configuration file with that name exists
1030 char filename [PATH_MAX];
1031 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1032 if(!access(filename, F_OK)) {
1033 fprintf(stderr, "A host config file for %s already exists!\n", name);
1037 // Ensure no other nodes know about this name
1038 if(meshlink_get_node(mesh, name)) {
1039 fprintf(stderr, "A node with name %s is already known!\n", name);
1043 if(!refresh_invitation_key(mesh))
1048 // Create a hash of the key.
1049 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1050 sha512(fingerprint, strlen(fingerprint), hash);
1051 b64encode_urlsafe(hash, hash, 18);
1053 // Create a random cookie for this invitation.
1055 randomize(cookie, 18);
1057 // Create a filename that doesn't reveal the cookie itself
1058 char buf[18 + strlen(fingerprint)];
1059 char cookiehash[64];
1060 memcpy(buf, cookie, 18);
1061 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1062 sha512(buf, sizeof buf, cookiehash);
1063 b64encode_urlsafe(cookiehash, cookiehash, 18);
1065 b64encode_urlsafe(cookie, cookie, 18);
1067 // Create a file containing the details of the invitation.
1068 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1069 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1071 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1074 FILE *f = fdopen(ifd, "w");
1078 // Get the local address
1079 char *address = get_my_hostname(mesh);
1081 // Fill in the details.
1082 fprintf(f, "Name = %s\n", name);
1084 // fprintf(f, "NetName = %s\n", netname);
1085 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1087 // Copy Broadcast and Mode
1088 FILE *tc = fopen(mesh->meshlink_conf, "r");
1091 while(fgets(buf, sizeof buf, tc)) {
1092 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1093 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1095 // Make sure there is a newline character.
1096 if(!strchr(buf, '\n'))
1103 fprintf(f, "#---------------------------------------------------------------#\n");
1104 fprintf(f, "Name = %s\n", mesh->self->name);
1106 char filename2[PATH_MAX];
1107 snprintf(filename2,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1108 fcopy(f, filename2);
1111 // Create an URL from the local address, key hash and cookie
1113 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1118 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1119 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1120 char copy[strlen(invitation) + 1];
1121 strcpy(copy, invitation);
1123 // Make sure confbase exists and is accessible.
1124 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1125 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1129 if(access(mesh->confbase, R_OK | W_OK | X_OK)) {
1130 fprintf(stderr, "No permission to write in directory %s: %s\n", mesh->confbase, strerror(errno));
1134 // TODO: Either remove or reintroduce netname in meshlink
1135 // If a netname or explicit configuration directory is specified, check for an existing meshlink.conf.
1136 //if((mesh->netname || confbasegiven) && !access(meshlink_conf, F_OK)) {
1137 // fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
1141 char *slash = strchr(copy, '/');
1147 if(strlen(slash) != 48)
1150 char *address = copy;
1152 if(*address == '[') {
1154 char *bracket = strchr(address, ']');
1158 if(bracket[1] == ':')
1161 port = strchr(address, ':');
1166 if(!mesh->myport || !*port)
1169 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1172 // Generate a throw-away key for the invitation.
1173 ecdsa_t *key = ecdsa_generate();
1177 char *b64key = ecdsa_get_base64_public_key(key);
1179 // Connect to the meshlink daemon mentioned in the URL.
1180 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1184 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1185 if(mesh->sock <= 0) {
1186 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1190 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1191 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1192 closesocket(mesh->sock);
1196 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1198 // Tell him we have an invitation, and give him our throw-away key.
1200 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1201 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1202 closesocket(mesh->sock);
1206 char hisname[4096] = "";
1207 int code, hismajor, hisminor = 0;
1209 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) {
1210 fprintf(stderr, "Cannot read greeting from peer\n");
1211 closesocket(mesh->sock);
1215 // Check if the hash of the key he gave us matches the hash in the URL.
1216 char *fingerprint = mesh->line + 2;
1218 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1219 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1222 if(memcmp(hishash, mesh->hash, 18)) {
1223 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1228 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1232 // Start an SPTPS session
1233 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1236 // Feed rest of input buffer to SPTPS
1237 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1242 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1246 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1250 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1254 sptps_stop(&mesh->sptps);
1257 closesocket(mesh->sock);
1259 if(!mesh->success) {
1260 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1267 fprintf(stderr, "Invalid invitation URL.\n");
1271 char *meshlink_export(meshlink_handle_t *mesh) {
1275 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1279 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1282 static void __attribute__((constructor)) meshlink_init(void) {
1286 static void __attribute__((destructor)) meshlink_exit(void) {