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"
41 static char meshlink_conf[PATH_MAX];
42 static char hosts_dir[PATH_MAX];
46 static char cookie[18], hash[18];
47 static char *data = NULL;
48 static size_t thedatalen = 0;
49 static bool success = false;
50 static char line[4096];
51 static char buffer[4096];
52 static size_t blen = 0;
54 const var_t variables[] = {
55 /* Server configuration */
56 {"AddressFamily", VAR_SERVER},
57 {"AutoConnect", VAR_SERVER | VAR_SAFE},
58 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
59 {"BindToInterface", VAR_SERVER},
60 {"Broadcast", VAR_SERVER | VAR_SAFE},
61 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
62 {"DecrementTTL", VAR_SERVER},
63 {"Device", VAR_SERVER},
64 {"DeviceType", VAR_SERVER},
65 {"DirectOnly", VAR_SERVER},
66 {"ECDSAPrivateKeyFile", VAR_SERVER},
67 {"ExperimentalProtocol", VAR_SERVER},
68 {"Forwarding", VAR_SERVER},
69 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
70 {"Hostnames", VAR_SERVER},
71 {"IffOneQueue", VAR_SERVER},
72 {"Interface", VAR_SERVER},
73 {"KeyExpire", VAR_SERVER},
74 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
75 {"LocalDiscovery", VAR_SERVER},
76 {"MACExpire", VAR_SERVER},
77 {"MaxConnectionBurst", VAR_SERVER},
78 {"MaxOutputBufferSize", VAR_SERVER},
79 {"MaxTimeout", VAR_SERVER},
80 {"Mode", VAR_SERVER | VAR_SAFE},
82 {"PingInterval", VAR_SERVER},
83 {"PingTimeout", VAR_SERVER},
84 {"PriorityInheritance", VAR_SERVER},
85 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
86 {"PrivateKeyFile", VAR_SERVER},
87 {"ProcessPriority", VAR_SERVER},
88 {"Proxy", VAR_SERVER},
89 {"ReplayWindow", VAR_SERVER},
90 {"ScriptsExtension", VAR_SERVER},
91 {"ScriptsInterpreter", VAR_SERVER},
92 {"StrictSubnets", VAR_SERVER},
93 {"TunnelServer", VAR_SERVER},
94 {"VDEGroup", VAR_SERVER},
95 {"VDEPort", VAR_SERVER},
96 /* Host configuration */
97 {"Address", VAR_HOST | VAR_MULTIPLE},
98 {"Cipher", VAR_SERVER | VAR_HOST},
99 {"ClampMSS", VAR_SERVER | VAR_HOST},
100 {"Compression", VAR_SERVER | VAR_HOST},
101 {"Digest", VAR_SERVER | VAR_HOST},
102 {"ECDSAPublicKey", VAR_HOST},
103 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
104 {"IndirectData", VAR_SERVER | VAR_HOST},
105 {"MACLength", VAR_SERVER | VAR_HOST},
106 {"PMTU", VAR_SERVER | VAR_HOST},
107 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
109 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
110 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
111 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
112 {"TCPOnly", VAR_SERVER | VAR_HOST},
113 {"Weight", VAR_HOST | VAR_SAFE},
117 static char *get_line(const char **data) {
126 static char line[1024];
127 const char *end = strchr(*data, '\n');
128 size_t len = end ? end - *data : strlen(*data);
129 if(len >= sizeof line) {
130 fprintf(stderr, "Maximum line length exceeded!\n");
133 if(len && !isprint(**data))
136 memcpy(line, *data, len);
147 static char *get_value(const char *data, const char *var) {
148 char *line = get_line(&data);
152 char *sep = line + strcspn(line, " \t=");
153 char *val = sep + strspn(sep, " \t");
155 val += 1 + strspn(val + 1, " \t");
157 if(strcasecmp(line, var))
161 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
162 mode_t mask = umask(0);
165 FILE *f = fopen(filename, mode);
167 if((perms & 0444) && f)
168 fchmod(fileno(f), perms);
174 static bool finalize_join(meshlink_handle_t *mesh) {
175 char *name = xstrdup(get_value(data, "Name"));
177 fprintf(stderr, "No Name found in invitation!\n");
181 if(!check_id(name)) {
182 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
186 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
187 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
191 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
192 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
196 FILE *f = fopen(meshlink_conf, "w");
198 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
202 fprintf(f, "Name = %s\n", name);
204 char filename[PATH_MAX];
205 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, name);
206 FILE *fh = fopen(filename, "w");
208 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
212 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
213 // Other chunks go unfiltered to their respective host config files
214 const char *p = data;
217 while((l = get_line(&p))) {
222 // Split line into variable and value
223 int len = strcspn(l, "\t =");
225 value += strspn(value, "\t ");
228 value += strspn(value, "\t ");
233 if(!strcasecmp(l, "Name"))
234 if(strcmp(value, name))
238 else if(!strcasecmp(l, "NetName"))
241 // Check the list of known variables
244 for(i = 0; variables[i].name; i++) {
245 if(strcasecmp(l, variables[i].name))
251 // Ignore unknown and unsafe variables
253 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
255 } else if(!(variables[i].type & VAR_SAFE)) {
256 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
260 // Copy the safe variable to the right config file
261 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
266 while(l && !strcasecmp(l, "Name")) {
267 if(!check_id(value)) {
268 fprintf(stderr, "Invalid Name found in invitation.\n");
272 if(!strcmp(value, name)) {
273 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
277 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, value);
278 f = fopen(filename, "w");
281 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
285 while((l = get_line(&p))) {
286 if(!strcmp(l, "#---------------------------------------------------------------#"))
288 int len = strcspn(l, "\t =");
289 if(len == 4 && !strncasecmp(l, "Name", 4)) {
291 value += strspn(value, "\t ");
294 value += strspn(value, "\t ");
307 // Generate our key and send a copy to the server
308 ecdsa_t *key = ecdsa_generate();
312 char *b64key = ecdsa_get_base64_public_key(key);
316 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
317 f = fopenmask(filename, "w", 0600);
319 if(!ecdsa_write_pem_private_key(key, f)) {
320 fprintf(stderr, "Error writing private key!\n");
328 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
330 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
337 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
342 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
344 int result = send(sock, data, len, 0);
345 if(result == -1 && errno == EINTR)
355 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
357 case SPTPS_HANDSHAKE:
358 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
361 data = xrealloc(data, thedatalen + len + 1);
362 memcpy(data + thedatalen, msg, len);
364 data[thedatalen] = 0;
368 return finalize_join(NULL);//TODO: wrong, we have to pass the mesh handler here, but how ?
371 fprintf(stderr, "Invitation succesfully accepted.\n");
372 shutdown(sock, SHUT_RDWR);
383 static bool recvline(int fd, char *line, size_t len) {
384 char *newline = NULL;
389 while(!(newline = memchr(buffer, '\n', blen))) {
390 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
391 if(result == -1 && errno == EINTR)
398 if(newline - buffer >= len)
401 len = newline - buffer;
403 memcpy(line, buffer, len);
405 memmove(buffer, newline + 1, blen - len - 1);
410 static bool sendline(int fd, char *format, ...) {
411 static char buffer[4096];
416 va_start(ap, format);
417 blen = vsnprintf(buffer, sizeof buffer, format, ap);
420 if(blen < 1 || blen >= sizeof buffer)
427 int result = send(fd, p, blen, MSG_NOSIGNAL);
428 if(result == -1 && errno == EINTR)
438 int rstrip(char *value) {
439 int len = strlen(value);
440 while(len && strchr("\t\r\n ", value[len - 1]))
446 static const char *errstr[] = {
447 [MESHLINK_OK] = "No error",
448 [MESHLINK_ENOMEM] = "Out of memory",
449 [MESHLINK_ENOENT] = "No such node",
452 const char *meshlink_strerror(meshlink_errno_t errno) {
453 return errstr[errno];
456 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
459 char pubname[PATH_MAX], privname[PATH_MAX];
461 fprintf(stderr, "Generating ECDSA keypair:\n");
463 if(!(key = ecdsa_generate())) {
464 fprintf(stderr, "Error during key generation!\n");
467 fprintf(stderr, "Done.\n");
469 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
470 f = fopen(privname, "w");
476 fchmod(fileno(f), 0600);
479 if(!ecdsa_write_pem_private_key(key, f)) {
480 fprintf(stderr, "Error writing private key!\n");
489 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
490 f = fopen(pubname, "a");
495 char *pubkey = ecdsa_get_base64_public_key(key);
496 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
505 static bool try_bind(int port) {
506 struct addrinfo *ai = NULL;
507 struct addrinfo hint = {
508 .ai_flags = AI_PASSIVE,
509 .ai_family = AF_UNSPEC,
510 .ai_socktype = SOCK_STREAM,
511 .ai_protocol = IPPROTO_TCP,
515 snprintf(portstr, sizeof portstr, "%d", port);
517 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
521 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
524 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
534 int check_port(meshlink_handle_t *mesh) {
538 fprintf(stderr, "Warning: could not bind to port 655.\n");
540 for(int i = 0; i < 100; i++) {
541 int port = 0x1000 + (rand() & 0x7fff);
543 char filename[PATH_MAX];
544 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
545 FILE *f = fopen(filename, "a");
547 fprintf(stderr, "Please change MeshLink's Port manually.\n");
551 fprintf(f, "Port = %d\n", port);
553 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
558 fprintf(stderr, "Please change MeshLink's Port manually.\n");
562 static bool meshlink_setup(meshlink_handle_t *mesh) {
564 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
565 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
569 snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
571 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
572 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
576 snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
578 if(!access(meshlink_conf, F_OK)) {
579 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
583 FILE *f = fopen(meshlink_conf, "w");
585 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
589 fprintf(f, "Name = %s\n", mesh->name);
592 if(!ecdsa_keygen(mesh))
600 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
601 // Validate arguments provided by the application
603 if(!confbase || !*confbase) {
604 fprintf(stderr, "No confbase given!\n");
608 if(!name || !*name) {
609 fprintf(stderr, "No name given!\n");
613 if(!check_id(name)) {
614 fprintf(stderr, "Invalid name given!\n");
618 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
619 mesh->confbase = xstrdup(confbase);
620 mesh->name = xstrdup(name);
621 event_loop_init(&mesh->loop);
622 mesh->loop.data = mesh;
624 // TODO: should be set by a function.
625 mesh->debug_level = 5;
627 // Check whether meshlink.conf already exists
629 char filename[PATH_MAX];
630 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
632 if(access(filename, R_OK)) {
633 if(errno == ENOENT) {
635 meshlink_setup(mesh);
637 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
638 return meshlink_close(mesh), NULL;
642 // Read the configuration
644 init_configuration(&mesh->config);
646 if(!read_server_config(mesh))
647 return meshlink_close(mesh), NULL;
649 // Setup up everything
650 // TODO: we should not open listening sockets yet
652 if(!setup_network(mesh))
653 return meshlink_close(mesh), NULL;
658 void *meshlink_main_loop(void *arg) {
659 meshlink_handle_t *mesh = arg;
661 try_outgoing_connections(mesh);
668 bool meshlink_start(meshlink_handle_t *mesh) {
669 // TODO: open listening sockets first
671 // Start the main thread
673 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
674 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
675 memset(&mesh->thread, 0, sizeof mesh->thread);
682 void meshlink_stop(meshlink_handle_t *mesh) {
683 // TODO: close the listening sockets to signal the main thread to shut down
685 // Wait for the main thread to finish
687 pthread_join(mesh->thread, NULL);
690 void meshlink_close(meshlink_handle_t *mesh) {
691 // Close and free all resources used.
693 close_network_connections(mesh);
695 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
697 exit_configuration(&mesh->config);
698 event_loop_exit(&mesh->loop);
701 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
702 mesh->receive_cb = cb;
705 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
706 mesh->node_status_cb = cb;
709 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
711 mesh->log_level = level;
714 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
716 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
717 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
722 packet.probe = false;
723 memset(hdr, 0, sizeof *hdr);
724 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
725 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
727 packet.len = sizeof *hdr + len;
728 memcpy(packet.data + sizeof *hdr, data, len);
730 mesh->self->in_packets++;
731 mesh->self->in_bytes += packet.len;
732 route(mesh, mesh->self, &packet);
736 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
737 return (meshlink_node_t *)lookup_node(mesh, name);
741 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
745 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
749 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
753 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
757 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
760 // Make sure confbase exists and is accessible.
761 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
762 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
766 if(access(mesh->confbase, R_OK | W_OK | X_OK)) {
767 fprintf(stderr, "No permission to write in directory %s: %s\n", mesh->confbase, strerror(errno));
771 // TODO: Either remove or reintroduce netname in meshlink
772 // If a netname or explicit configuration directory is specified, check for an existing meshlink.conf.
773 //if((mesh->netname || confbasegiven) && !access(meshlink_conf, F_OK)) {
774 // fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
778 char *slash = strchr(invitation, '/');
784 if(strlen(slash) != 48)
787 char *address = invitation;
789 if(*address == '[') {
791 char *bracket = strchr(address, ']');
795 if(bracket[1] == ':')
798 port = strchr(address, ':');
803 if(!mesh->myport || !*port)
806 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
809 // Generate a throw-away key for the invitation.
810 ecdsa_t *key = ecdsa_generate();
814 char *b64key = ecdsa_get_base64_public_key(key);
816 // Connect to the meshlink daemon mentioned in the URL.
817 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
821 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
823 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
827 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
828 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
833 fprintf(stderr, "Connected to %s port %s...\n", address, port);
835 // Tell him we have an invitation, and give him our throw-away key.
836 int len = snprintf(invitation, sizeof invitation, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
837 if(len <= 0 || len >= sizeof invitation)
840 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
841 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
846 char hisname[4096] = "";
847 int code, hismajor, hisminor = 0;
849 if(!recvline(sock, line, sizeof line) || sscanf(line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(sock, line, sizeof line) || !rstrip(line) || sscanf(line, "%d ", &code) != 1 || code != ACK || strlen(line) < 3) {
850 fprintf(stderr, "Cannot read greeting from peer\n");
855 // Check if the hash of the key he gave us matches the hash in the URL.
856 char *fingerprint = line + 2;
858 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
859 fprintf(stderr, "Could not create hash\n%s\n", line + 2);
862 if(memcmp(hishash, hash, 18)) {
863 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
868 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
872 // Start an SPTPS session
873 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
876 // Feed rest of input buffer to SPTPS
877 if(!sptps_receive_data(&sptps, buffer, blen))
880 while((len = recv(sock, line, sizeof line, 0))) {
884 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
888 if(!sptps_receive_data(&sptps, line, len))
898 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
905 fprintf(stderr, "Invalid invitation URL.\n");
909 char *meshlink_export(meshlink_handle_t *mesh) {
913 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
917 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
920 static void __attribute__((constructor)) meshlink_init(void) {
924 static void __attribute__((destructor)) meshlink_exit(void) {