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))
345 static bool try_bind(int port) {
346 struct addrinfo *ai = NULL;
347 struct addrinfo hint = {
348 .ai_flags = AI_PASSIVE,
349 .ai_family = AF_UNSPEC,
350 .ai_socktype = SOCK_STREAM,
351 .ai_protocol = IPPROTO_TCP,
355 snprintf(portstr, sizeof portstr, "%d", port);
357 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
361 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
364 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
374 static int check_port(meshlink_handle_t *mesh) {
378 fprintf(stderr, "Warning: could not bind to port 655.\n");
380 for(int i = 0; i < 100; i++) {
381 int port = 0x1000 + (rand() & 0x7fff);
383 char filename[PATH_MAX];
384 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
385 FILE *f = fopen(filename, "a");
387 fprintf(stderr, "Please change MeshLink's Port manually.\n");
391 fprintf(f, "Port = %d\n", port);
393 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
398 fprintf(stderr, "Please change MeshLink's Port manually.\n");
402 static bool finalize_join(meshlink_handle_t *mesh) {
403 char *name = xstrdup(get_value(mesh->data, "Name"));
405 fprintf(stderr, "No Name found in invitation!\n");
409 if(!check_id(name)) {
410 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
414 char filename[PATH_MAX];
415 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
417 FILE *f = fopen(filename, "w");
419 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
423 fprintf(f, "Name = %s\n", name);
425 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
426 FILE *fh = fopen(filename, "w");
428 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
432 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
433 // Other chunks go unfiltered to their respective host config files
434 const char *p = mesh->data;
437 while((l = get_line(&p))) {
442 // Split line into variable and value
443 int len = strcspn(l, "\t =");
445 value += strspn(value, "\t ");
448 value += strspn(value, "\t ");
453 if(!strcasecmp(l, "Name"))
454 if(strcmp(value, name))
458 else if(!strcasecmp(l, "NetName"))
461 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
464 for(i = 0; variables[i].name; i++) {
465 if(strcasecmp(l, variables[i].name))
471 // Ignore unknown and unsafe variables
473 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
475 } else if(!(variables[i].type & VAR_SAFE)) {
476 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
480 // Copy the safe variable to the right config file
481 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
486 while(l && !strcasecmp(l, "Name")) {
487 if(!check_id(value)) {
488 fprintf(stderr, "Invalid Name found in invitation.\n");
492 if(!strcmp(value, name)) {
493 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
497 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
498 f = fopen(filename, "w");
501 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
505 while((l = get_line(&p))) {
506 if(!strcmp(l, "#---------------------------------------------------------------#"))
508 int len = strcspn(l, "\t =");
509 if(len == 4 && !strncasecmp(l, "Name", 4)) {
511 value += strspn(value, "\t ");
514 value += strspn(value, "\t ");
527 char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
531 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
532 fprintf(fh, "Port = %s\n", mesh->myport);
536 sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
539 free(mesh->self->name);
540 free(mesh->self->connection->name);
541 mesh->self->name = xstrdup(name);
542 mesh->self->connection->name = xstrdup(name);
544 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
546 load_all_nodes(mesh);
551 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
552 meshlink_handle_t* mesh = handle;
554 int result = send(mesh->sock, data, len, 0);
555 if(result == -1 && errno == EINTR)
565 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
566 meshlink_handle_t* mesh = handle;
568 case SPTPS_HANDSHAKE:
569 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
572 mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
573 memcpy(mesh->data + mesh->thedatalen, msg, len);
574 mesh->thedatalen += len;
575 mesh->data[mesh->thedatalen] = 0;
579 return finalize_join(mesh);
582 fprintf(stderr, "Invitation succesfully accepted.\n");
583 shutdown(mesh->sock, SHUT_RDWR);
584 mesh->success = true;
594 static bool recvline(meshlink_handle_t* mesh, size_t len) {
595 char *newline = NULL;
600 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
601 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
602 if(result == -1 && errno == EINTR)
606 mesh->blen += result;
609 if(newline - mesh->buffer >= len)
612 len = newline - mesh->buffer;
614 memcpy(mesh->line, mesh->buffer, len);
616 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
617 mesh->blen -= len + 1;
621 static bool sendline(int fd, char *format, ...) {
622 static char buffer[4096];
627 va_start(ap, format);
628 blen = vsnprintf(buffer, sizeof buffer, format, ap);
631 if(blen < 1 || blen >= sizeof buffer)
638 int result = send(fd, p, blen, MSG_NOSIGNAL);
639 if(result == -1 && errno == EINTR)
650 static const char *errstr[] = {
651 [MESHLINK_OK] = "No error",
652 [MESHLINK_ENOMEM] = "Out of memory",
653 [MESHLINK_ENOENT] = "No such node",
656 const char *meshlink_strerror(meshlink_errno_t errno) {
657 return errstr[errno];
660 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
663 char pubname[PATH_MAX], privname[PATH_MAX];
665 fprintf(stderr, "Generating ECDSA keypair:\n");
667 if(!(key = ecdsa_generate())) {
668 fprintf(stderr, "Error during key generation!\n");
671 fprintf(stderr, "Done.\n");
673 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
674 f = fopen(privname, "w");
680 fchmod(fileno(f), 0600);
683 if(!ecdsa_write_pem_private_key(key, f)) {
684 fprintf(stderr, "Error writing private key!\n");
693 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
694 f = fopen(pubname, "a");
699 char *pubkey = ecdsa_get_base64_public_key(key);
700 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
709 static bool meshlink_setup(meshlink_handle_t *mesh) {
710 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
711 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
715 char filename[PATH_MAX];
716 snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
718 if(mkdir(filename, 0777) && errno != EEXIST) {
719 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
723 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
725 if(!access(filename, F_OK)) {
726 fprintf(stderr, "Configuration file %s already exists!\n", filename);
730 FILE *f = fopen(filename, "w");
732 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
736 fprintf(f, "Name = %s\n", mesh->name);
739 if(!ecdsa_keygen(mesh))
747 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
748 // Validate arguments provided by the application
750 if(!confbase || !*confbase) {
751 fprintf(stderr, "No confbase given!\n");
755 if(!name || !*name) {
756 fprintf(stderr, "No name given!\n");
760 if(!check_id(name)) {
761 fprintf(stderr, "Invalid name given!\n");
765 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
766 mesh->confbase = xstrdup(confbase);
767 mesh->name = xstrdup(name);
768 event_loop_init(&mesh->loop);
769 mesh->loop.data = mesh;
771 // TODO: should be set by a function.
772 mesh->debug_level = 5;
774 // Check whether meshlink.conf already exists
776 char filename[PATH_MAX];
777 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
779 if(access(filename, R_OK)) {
780 if(errno == ENOENT) {
782 meshlink_setup(mesh);
784 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
785 return meshlink_close(mesh), NULL;
789 // Read the configuration
791 init_configuration(&mesh->config);
793 if(!read_server_config(mesh))
794 return meshlink_close(mesh), NULL;
796 // Setup up everything
797 // TODO: we should not open listening sockets yet
799 if(!setup_network(mesh))
800 return meshlink_close(mesh), NULL;
805 void *meshlink_main_loop(void *arg) {
806 meshlink_handle_t *mesh = arg;
808 try_outgoing_connections(mesh);
815 bool meshlink_start(meshlink_handle_t *mesh) {
816 // TODO: open listening sockets first
818 // Start the main thread
820 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
821 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
822 memset(&mesh->thread, 0, sizeof mesh->thread);
829 void meshlink_stop(meshlink_handle_t *mesh) {
830 // TODO: close the listening sockets to signal the main thread to shut down
832 // Wait for the main thread to finish
834 pthread_join(mesh->thread, NULL);
837 void meshlink_close(meshlink_handle_t *mesh) {
838 // Close and free all resources used.
840 close_network_connections(mesh);
842 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
844 exit_configuration(&mesh->config);
845 event_loop_exit(&mesh->loop);
848 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
849 mesh->receive_cb = cb;
852 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
853 mesh->node_status_cb = cb;
856 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
858 mesh->log_level = level;
861 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
863 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
864 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
869 packet.probe = false;
870 memset(hdr, 0, sizeof *hdr);
871 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
872 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
874 packet.len = sizeof *hdr + len;
875 memcpy(packet.data + sizeof *hdr, data, len);
877 mesh->self->in_packets++;
878 mesh->self->in_bytes += packet.len;
879 route(mesh, mesh->self, &packet);
883 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
884 return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
887 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
890 for splay_each(node_t, n, mesh->nodes) {
892 nodes[i] = (meshlink_node_t *)n;
899 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
903 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
907 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
908 char filename[PATH_MAX];
910 snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
911 if(mkdir(filename, 0700) && errno != EEXIST) {
912 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
916 // Count the number of valid invitations, clean up old ones
917 DIR *dir = opendir(filename);
919 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
926 time_t deadline = time(NULL) - 604800; // 1 week in the past
928 while((ent = readdir(dir))) {
929 if(strlen(ent->d_name) != 24)
931 char invname[PATH_MAX];
933 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
934 if(!stat(invname, &st)) {
935 if(mesh->invitation_key && deadline < st.st_mtime)
940 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
946 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
953 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
955 // Remove the key if there are no outstanding invitations.
958 if(mesh->invitation_key) {
959 ecdsa_free(mesh->invitation_key);
960 mesh->invitation_key = NULL;
964 if(mesh->invitation_key)
967 // Create a new key if necessary.
968 FILE *f = fopen(filename, "r");
970 if(errno != ENOENT) {
971 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
975 mesh->invitation_key = ecdsa_generate();
976 if(!mesh->invitation_key) {
977 fprintf(stderr, "Could not generate a new key!\n");
980 f = fopen(filename, "w");
982 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
985 chmod(filename, 0600);
986 ecdsa_write_pem_private_key(mesh->invitation_key, f);
989 mesh->invitation_key = ecdsa_read_pem_private_key(f);
991 if(!mesh->invitation_key)
992 fprintf(stderr, "Could not read private key from %s\n", filename);
995 return mesh->invitation_key;
998 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
999 // Check validity of the new node's name
1000 if(!check_id(name)) {
1001 fprintf(stderr, "Invalid name for node.\n");
1005 // Ensure no host configuration file with that name exists
1006 char filename[PATH_MAX];
1007 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1008 if(!access(filename, F_OK)) {
1009 fprintf(stderr, "A host config file for %s already exists!\n", name);
1013 // Ensure no other nodes know about this name
1014 if(meshlink_get_node(mesh, name)) {
1015 fprintf(stderr, "A node with name %s is already known!\n", name);
1019 if(!refresh_invitation_key(mesh))
1024 // Create a hash of the key.
1025 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1026 sha512(fingerprint, strlen(fingerprint), hash);
1027 b64encode_urlsafe(hash, hash, 18);
1029 // Create a random cookie for this invitation.
1031 randomize(cookie, 18);
1033 // Create a filename that doesn't reveal the cookie itself
1034 char buf[18 + strlen(fingerprint)];
1035 char cookiehash[64];
1036 memcpy(buf, cookie, 18);
1037 memcpy(buf + 18, fingerprint, sizeof buf - 18);
1038 sha512(buf, sizeof buf, cookiehash);
1039 b64encode_urlsafe(cookiehash, cookiehash, 18);
1041 b64encode_urlsafe(cookie, cookie, 18);
1043 // Create a file containing the details of the invitation.
1044 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1045 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1047 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1050 FILE *f = fdopen(ifd, "w");
1054 // Get the local address
1055 char *address = get_my_hostname(mesh);
1057 // Fill in the details.
1058 fprintf(f, "Name = %s\n", name);
1060 // fprintf(f, "NetName = %s\n", netname);
1061 fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1063 // Copy Broadcast and Mode
1064 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1065 FILE *tc = fopen(filename, "r");
1068 while(fgets(buf, sizeof buf, tc)) {
1069 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1070 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1072 // Make sure there is a newline character.
1073 if(!strchr(buf, '\n'))
1079 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1083 fprintf(f, "#---------------------------------------------------------------#\n");
1084 fprintf(f, "Name = %s\n", mesh->self->name);
1086 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1090 // Create an URL from the local address, key hash and cookie
1092 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1097 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1098 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1099 char copy[strlen(invitation) + 1];
1100 strcpy(copy, invitation);
1102 // Split the invitation URL into hostname, port, key hash and cookie.
1104 char *slash = strchr(copy, '/');
1110 if(strlen(slash) != 48)
1113 char *address = copy;
1115 if(*address == '[') {
1117 char *bracket = strchr(address, ']');
1121 if(bracket[1] == ':')
1124 port = strchr(address, ':');
1132 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1135 // Generate a throw-away key for the invitation.
1136 ecdsa_t *key = ecdsa_generate();
1140 char *b64key = ecdsa_get_base64_public_key(key);
1142 // Connect to the meshlink daemon mentioned in the URL.
1143 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1147 mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1148 if(mesh->sock <= 0) {
1149 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1153 if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1154 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1155 closesocket(mesh->sock);
1159 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1161 // Tell him we have an invitation, and give him our throw-away key.
1165 if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1166 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1167 closesocket(mesh->sock);
1171 char hisname[4096] = "";
1172 int code, hismajor, hisminor = 0;
1174 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) {
1175 fprintf(stderr, "Cannot read greeting from peer\n");
1176 closesocket(mesh->sock);
1180 // Check if the hash of the key he gave us matches the hash in the URL.
1181 char *fingerprint = mesh->line + 2;
1183 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1184 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1187 if(memcmp(hishash, mesh->hash, 18)) {
1188 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1193 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1197 // Start an SPTPS session
1198 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1201 // Feed rest of input buffer to SPTPS
1202 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1207 while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1211 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1215 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1219 sptps_stop(&mesh->sptps);
1222 closesocket(mesh->sock);
1224 if(!mesh->success) {
1225 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1232 fprintf(stderr, "Invalid invitation URL.\n");
1236 char *meshlink_export(meshlink_handle_t *mesh) {
1240 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1244 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1247 static void __attribute__((constructor)) meshlink_init(void) {
1251 static void __attribute__((destructor)) meshlink_exit(void) {