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 char *get_my_name(meshlink_handle_t* mesh) {
107 FILE *f = fopen(mesh->meshlink_conf, "r");
114 while(fgets(buf, sizeof buf, f)) {
115 int len = strcspn(buf, "\t =");
117 value += strspn(value, "\t ");
120 value += strspn(value, "\t ");
125 if(strcasecmp(buf, "Name"))
129 return strdup(value);
136 static bool fcopy(FILE *out, const char *filename) {
137 FILE *in = fopen(filename, "r");
139 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
145 while((len = fread(buf, 1, sizeof buf, in)))
146 fwrite(buf, len, 1, out);
150 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
152 if(!filename || (*hostname && *port))
155 FILE *f = fopen(filename, "r");
159 while(fgets(line, sizeof line, f)) {
163 p += strcspn(p, "\t =");
166 q = p + strspn(p, "\t ");
168 q += 1 + strspn(q + 1, "\t ");
170 p = q + strcspn(q, "\t ");
173 p += strspn(p, "\t ");
174 p[strcspn(p, "\t ")] = 0;
176 if(!*port && !strcasecmp(line, "Port")) {
178 } else if(!*hostname && !strcasecmp(line, "Address")) {
179 *hostname = xstrdup(q);
186 if(*hostname && *port)
192 static char *get_my_hostname(meshlink_handle_t* mesh) {
193 char *hostname = NULL;
195 char *hostport = NULL;
196 char *name = get_my_name(mesh);
197 char filename[PATH_MAX];
200 // Use first Address statement in own host config file
202 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
203 scan_for_hostname(filename, &hostname, &port);
204 scan_for_hostname(mesh->meshlink_conf, &hostname, &port);
210 // If that doesn't work, guess externally visible hostname
211 fprintf(stderr, "Trying to discover externally visible hostname...\n");
212 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
213 struct addrinfo *aip = ai;
214 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
217 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
219 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
225 send(s, request, sizeof request - 1, 0);
226 int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
229 if(line[len - 1] == '\n')
231 char *p = strrchr(line, '\n');
233 hostname = xstrdup(p + 1);
246 // Check that the hostname is reasonable
248 for(char *p = hostname; *p; p++) {
249 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
251 // If not, forget it.
260 // fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
267 fprintf(stderr, "Please enter your host's external address or hostname");
269 fprintf(stderr, " [%s]", hostname);
270 fprintf(stderr, ": ");
272 if(!fgets(line, sizeof line, stdin)) {
273 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
285 for(char *p = line; *p; p++) {
286 if(isalnum(*p) || *p == '-' || *p == '.')
288 fprintf(stderr, "Invalid address or hostname.\n");
293 hostname = xstrdup(line);
297 FILE *f = fopen(filename, "a");
299 fprintf(f, "\nAddress = %s\n", hostname);
302 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
308 if(strchr(hostname, ':'))
309 xasprintf(&hostport, "[%s]:%s", hostname, port);
311 xasprintf(&hostport, "%s:%s", hostname, port);
313 if(strchr(hostname, ':'))
314 xasprintf(&hostport, "[%s]", hostname);
316 hostport = xstrdup(hostname);
324 static char *get_line(const char **data) {
333 static char line[1024];
334 const char *end = strchr(*data, '\n');
335 size_t len = end ? end - *data : strlen(*data);
336 if(len >= sizeof line) {
337 fprintf(stderr, "Maximum line length exceeded!\n");
340 if(len && !isprint(**data))
343 memcpy(line, *data, len);
354 static char *get_value(const char *data, const char *var) {
355 char *line = get_line(&data);
359 char *sep = line + strcspn(line, " \t=");
360 char *val = sep + strspn(sep, " \t");
362 val += 1 + strspn(val + 1, " \t");
364 if(strcasecmp(line, var))
368 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
369 mode_t mask = umask(0);
372 FILE *f = fopen(filename, mode);
374 if((perms & 0444) && f)
375 fchmod(fileno(f), perms);
381 static bool finalize_join(meshlink_handle_t *mesh) {
382 char *name = xstrdup(get_value(mesh->data, "Name"));
384 fprintf(stderr, "No Name found in invitation!\n");
388 if(!check_id(name)) {
389 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
393 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
394 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
398 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
399 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
403 FILE *f = fopen(mesh->meshlink_conf, "w");
405 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
409 fprintf(f, "Name = %s\n", name);
411 char filename[PATH_MAX];
412 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, name);
413 FILE *fh = fopen(filename, "w");
415 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
419 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
420 // Other chunks go unfiltered to their respective host config files
421 const char *p = mesh->data;
424 while((l = get_line(&p))) {
429 // Split line into variable and value
430 int len = strcspn(l, "\t =");
432 value += strspn(value, "\t ");
435 value += strspn(value, "\t ");
440 if(!strcasecmp(l, "Name"))
441 if(strcmp(value, name))
445 else if(!strcasecmp(l, "NetName"))
448 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
451 for(i = 0; variables[i].name; i++) {
452 if(strcasecmp(l, variables[i].name))
458 // Ignore unknown and unsafe variables
460 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
462 } else if(!(variables[i].type & VAR_SAFE)) {
463 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
467 // Copy the safe variable to the right config file
468 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
473 while(l && !strcasecmp(l, "Name")) {
474 if(!check_id(value)) {
475 fprintf(stderr, "Invalid Name found in invitation.\n");
479 if(!strcmp(value, name)) {
480 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
484 snprintf(filename,PATH_MAX, "%s" SLASH "%s", mesh->hosts_dir, value);
485 f = fopen(filename, "w");
488 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
492 while((l = get_line(&p))) {
493 if(!strcmp(l, "#---------------------------------------------------------------#"))
495 int len = strcspn(l, "\t =");
496 if(len == 4 && !strncasecmp(l, "Name", 4)) {
498 value += strspn(value, "\t ");
501 value += strspn(value, "\t ");
514 // Generate our key and send a copy to the server
515 ecdsa_t *key = ecdsa_generate();
519 char *b64key = ecdsa_get_base64_public_key(key);
523 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
524 f = fopenmask(filename, "w", 0600);
526 if(!ecdsa_write_pem_private_key(key, f)) {
527 fprintf(stderr, "Error writing private key!\n");
535 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
537 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
544 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
549 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
550 meshlink_handle_t* mesh = handle;
552 int result = send(mesh->sock, data, len, 0);
553 if(result == -1 && errno == EINTR)
563 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
564 meshlink_handle_t* mesh = handle;
566 case SPTPS_HANDSHAKE:
567 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
570 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
571 memcpy(mesh->data + mesh->thedatalen, msg, len);
572 mesh->thedatalen += len;
573 mesh->data[mesh->thedatalen] = 0;
577 return finalize_join(mesh);
580 fprintf(stderr, "Invitation succesfully accepted.\n");
581 shutdown(mesh->sock, SHUT_RDWR);
582 mesh->success = true;
592 static bool recvline(meshlink_handle_t* mesh, size_t len) {
593 char *newline = NULL;
598 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
599 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
600 if(result == -1 && errno == EINTR)
604 mesh->blen += result;
607 if(newline - mesh->buffer >= len)
610 len = newline - mesh->buffer;
612 memcpy(mesh->line, mesh->buffer, len);
614 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
615 mesh->blen -= len + 1;
619 static bool sendline(int fd, char *format, ...) {
620 static char buffer[4096];
625 va_start(ap, format);
626 blen = vsnprintf(buffer, sizeof buffer, format, ap);
629 if(blen < 1 || blen >= sizeof buffer)
636 int result = send(fd, p, blen, MSG_NOSIGNAL);
637 if(result == -1 && errno == EINTR)
647 int rstrip(char *value) {
648 int len = strlen(value);
649 while(len && strchr("\t\r\n ", value[len - 1]))
655 static const char *errstr[] = {
656 [MESHLINK_OK] = "No error",
657 [MESHLINK_ENOMEM] = "Out of memory",
658 [MESHLINK_ENOENT] = "No such node",
661 const char *meshlink_strerror(meshlink_errno_t errno) {
662 return errstr[errno];
665 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
668 char pubname[PATH_MAX], privname[PATH_MAX];
670 fprintf(stderr, "Generating ECDSA keypair:\n");
672 if(!(key = ecdsa_generate())) {
673 fprintf(stderr, "Error during key generation!\n");
676 fprintf(stderr, "Done.\n");
678 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
679 f = fopen(privname, "w");
685 fchmod(fileno(f), 0600);
688 if(!ecdsa_write_pem_private_key(key, f)) {
689 fprintf(stderr, "Error writing private key!\n");
698 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
699 f = fopen(pubname, "a");
704 char *pubkey = ecdsa_get_base64_public_key(key);
705 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
714 static bool try_bind(int port) {
715 struct addrinfo *ai = NULL;
716 struct addrinfo hint = {
717 .ai_flags = AI_PASSIVE,
718 .ai_family = AF_UNSPEC,
719 .ai_socktype = SOCK_STREAM,
720 .ai_protocol = IPPROTO_TCP,
724 snprintf(portstr, sizeof portstr, "%d", port);
726 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
730 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
733 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
743 int check_port(meshlink_handle_t *mesh) {
747 fprintf(stderr, "Warning: could not bind to port 655.\n");
749 for(int i = 0; i < 100; i++) {
750 int port = 0x1000 + (rand() & 0x7fff);
752 char filename[PATH_MAX];
753 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
754 FILE *f = fopen(filename, "a");
756 fprintf(stderr, "Please change MeshLink's Port manually.\n");
760 fprintf(f, "Port = %d\n", port);
762 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
767 fprintf(stderr, "Please change MeshLink's Port manually.\n");
771 static bool meshlink_setup(meshlink_handle_t *mesh) {
773 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
774 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
778 snprintf(mesh->hosts_dir, sizeof mesh->hosts_dir, "%s" SLASH "hosts", mesh->confbase);
780 if(mkdir(mesh->hosts_dir, 0777) && errno != EEXIST) {
781 fprintf(stderr, "Could not create directory %s: %s\n", mesh->hosts_dir, strerror(errno));
785 snprintf(mesh->meshlink_conf, sizeof mesh->meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
787 if(!access(mesh->meshlink_conf, F_OK)) {
788 fprintf(stderr, "Configuration file %s already exists!\n", mesh->meshlink_conf);
792 FILE *f = fopen(mesh->meshlink_conf, "w");
794 fprintf(stderr, "Could not create file %s: %s\n", mesh->meshlink_conf, strerror(errno));
798 fprintf(f, "Name = %s\n", mesh->name);
801 if(!ecdsa_keygen(mesh))
809 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
810 // Validate arguments provided by the application
812 if(!confbase || !*confbase) {
813 fprintf(stderr, "No confbase given!\n");
817 if(!name || !*name) {
818 fprintf(stderr, "No name given!\n");
822 if(!check_id(name)) {
823 fprintf(stderr, "Invalid name given!\n");
827 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
828 mesh->confbase = xstrdup(confbase);
829 mesh->name = xstrdup(name);
830 event_loop_init(&mesh->loop);
831 mesh->loop.data = mesh;
833 // TODO: should be set by a function.
834 mesh->debug_level = 5;
836 // Check whether meshlink.conf already exists
838 char filename[PATH_MAX];
839 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
841 if(access(filename, R_OK)) {
842 if(errno == ENOENT) {
844 meshlink_setup(mesh);
846 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
847 return meshlink_close(mesh), NULL;
851 // Read the configuration
853 init_configuration(&mesh->config);
855 if(!read_server_config(mesh))
856 return meshlink_close(mesh), NULL;
858 // Setup up everything
859 // TODO: we should not open listening sockets yet
861 if(!setup_network(mesh))
862 return meshlink_close(mesh), NULL;
867 void *meshlink_main_loop(void *arg) {
868 meshlink_handle_t *mesh = arg;
870 try_outgoing_connections(mesh);
877 bool meshlink_start(meshlink_handle_t *mesh) {
878 // TODO: open listening sockets first
880 // Start the main thread
882 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
883 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
884 memset(&mesh->thread, 0, sizeof mesh->thread);
891 void meshlink_stop(meshlink_handle_t *mesh) {
892 // TODO: close the listening sockets to signal the main thread to shut down
894 // Wait for the main thread to finish
896 pthread_join(mesh->thread, NULL);
899 void meshlink_close(meshlink_handle_t *mesh) {
900 // Close and free all resources used.
902 close_network_connections(mesh);
904 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
906 exit_configuration(&mesh->config);
907 event_loop_exit(&mesh->loop);
910 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
911 mesh->receive_cb = cb;
914 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
915 mesh->node_status_cb = cb;
918 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
920 mesh->log_level = level;
923 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
925 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
926 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
931 packet.probe = false;
932 memset(hdr, 0, sizeof *hdr);
933 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
934 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
936 packet.len = sizeof *hdr + len;
937 memcpy(packet.data + sizeof *hdr, data, len);
939 mesh->self->in_packets++;
940 mesh->self->in_bytes += packet.len;
941 route(mesh, mesh->self, &packet);
945 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
946 return (meshlink_node_t *)lookup_node(mesh, name);
950 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
954 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
958 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
962 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
963 // Check validity of the new node's name
964 if(!check_id(name)) {
965 fprintf(stderr, "Invalid name for node.\n");
969 char *myname = get_my_name(mesh);
971 fprintf(stderr, "Could not determine my own name.\n");
975 // Ensure no host configuration file with that name exists
976 char filename [PATH_MAX];
977 snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
978 if(!access(filename, F_OK)) {
979 fprintf(stderr, "A host config file for %s already exists!\n", name);
983 // If a daemon is running, ensure no other nodes know about this name
985 //TODO: original tinc code connects to tincd cli and makes this check. How we want to implement this here ?
986 //bool found = false;
987 //if(connect_tincd(false)) {
988 // sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
990 // while(recvline(fd, line, sizeof line)) {
993 // if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
995 // if(!strcmp(node, name))
1000 // fprintf(stderr, "A node with name %s is already known!\n", name);
1007 snprintf(filename,PATH_MAX, "%s" SLASH "invitations", mesh->confbase);
1008 if(mkdir(filename, 0700) && errno != EEXIST) {
1009 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1013 // Count the number of valid invitations, clean up old ones
1014 DIR *dir = opendir(filename);
1016 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1023 time_t deadline = time(NULL) - 604800; // 1 week in the past
1025 while((ent = readdir(dir))) {
1026 if(strlen(ent->d_name) != 24)
1028 char invname[PATH_MAX];
1030 snprintf(invname,PATH_MAX, "%s" SLASH "%s", filename, ent->d_name);
1031 if(!stat(invname, &st)) {
1032 if(deadline < st.st_mtime)
1037 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1043 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1051 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1053 // Remove the key if there are no outstanding invitations.
1057 // Create a new key if necessary.
1058 FILE *f = fopen(filename, "r");
1060 if(errno != ENOENT) {
1061 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1065 key = ecdsa_generate();
1067 fprintf(stderr, "Could not generate a new key!\n");
1070 f = fopen(filename, "w");
1072 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1075 chmod(filename, 0600);
1076 ecdsa_write_pem_private_key(key, f);
1078 //TODO: handle this in meshlink
1079 //if(connect_tincd(false))
1080 // sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1082 key = ecdsa_read_pem_private_key(f);
1085 fprintf(stderr, "Could not read private key from %s\n", filename);
1091 // Create a hash of the key.
1092 char *fingerprint = ecdsa_get_base64_public_key(key);
1093 sha512(fingerprint, strlen(fingerprint), hash);
1094 b64encode_urlsafe(hash, hash, 18);
1096 // Create a random cookie for this invitation.
1098 randomize(cookie, 18);
1100 // Create a filename that doesn't reveal the cookie itself
1101 char buf[18 + strlen(fingerprint)];
1102 char cookiehash[64];
1103 memcpy(buf, cookie, 18);
1104 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1105 sha512(buf, sizeof buf, cookiehash);
1106 b64encode_urlsafe(cookiehash, cookiehash, 18);
1108 b64encode_urlsafe(cookie, cookie, 18);
1110 // Create a file containing the details of the invitation.
1111 snprintf(filename,PATH_MAX, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1112 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1114 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1117 f = fdopen(ifd, "w");
1121 // Get the local address
1122 char *address = get_my_hostname(mesh);
1124 // Fill in the details.
1125 fprintf(f, "Name = %s\n", name);
1127 // fprintf(f, "NetName = %s\n", netname);
1128 fprintf(f, "ConnectTo = %s\n", myname);
1130 // Copy Broadcast and Mode
1131 FILE *tc = fopen(mesh->meshlink_conf, "r");
1134 while(fgets(buf, sizeof buf, tc)) {
1135 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1136 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1138 // Make sure there is a newline character.
1139 if(!strchr(buf, '\n'))
1146 fprintf(f, "#---------------------------------------------------------------#\n");
1147 fprintf(f, "Name = %s\n", myname);
1149 char filename2[PATH_MAX];
1150 snprintf(filename2,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, myname);
1151 fcopy(f, filename2);
1154 // Create an URL from the local address, key hash and cookie
1156 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1161 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1164 // Make sure confbase exists and is accessible.
1165 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
1166 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
1170 if(access(mesh->confbase, R_OK | W_OK | X_OK)) {
1171 fprintf(stderr, "No permission to write in directory %s: %s\n", mesh->confbase, strerror(errno));
1175 // TODO: Either remove or reintroduce netname in meshlink
1176 // If a netname or explicit configuration directory is specified, check for an existing meshlink.conf.
1177 //if((mesh->netname || confbasegiven) && !access(meshlink_conf, F_OK)) {
1178 // fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
1182 char *slash = strchr(invitation, '/');
1188 if(strlen(slash) != 48)
1191 char *address = invitation;
1193 if(*address == '[') {
1195 char *bracket = strchr(address, ']');
1199 if(bracket[1] == ':')
1202 port = strchr(address, ':');
1207 if(!mesh->myport || !*port)
1210 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1213 // Generate a throw-away key for the invitation.
1214 ecdsa_t *key = ecdsa_generate();
1218 char *b64key = ecdsa_get_base64_public_key(key);
1220 // Connect to the meshlink daemon mentioned in the URL.
1221 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1225 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1226 if(mesh->sock <= 0) {
1227 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1231 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1232 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1233 closesocket(mesh->sock);
1237 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1239 // Tell him we have an invitation, and give him our throw-away key.
1240 int len = snprintf(invitation, sizeof invitation, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1241 if(len <= 0 || len >= sizeof invitation)
1244 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1245 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1246 closesocket(mesh->sock);
1250 char hisname[4096] = "";
1251 int code, hismajor, hisminor = 0;
1253 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) {
1254 fprintf(stderr, "Cannot read greeting from peer\n");
1255 closesocket(mesh->sock);
1259 // Check if the hash of the key he gave us matches the hash in the URL.
1260 char *fingerprint = mesh->line + 2;
1262 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
1263 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1266 if(memcmp(hishash, mesh->hash, 18)) {
1267 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1272 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1276 // Start an SPTPS session
1277 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1280 // Feed rest of input buffer to SPTPS
1281 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1284 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1288 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1292 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1296 sptps_stop(&mesh->sptps);
1299 closesocket(mesh->sock);
1301 if(!mesh->success) {
1302 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1309 fprintf(stderr, "Invalid invitation URL.\n");
1313 char *meshlink_export(meshlink_handle_t *mesh) {
1317 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1321 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1324 static void __attribute__((constructor)) meshlink_init(void) {
1328 static void __attribute__((destructor)) meshlink_exit(void) {