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 //TODO: move all of this to meshlink_handle_t
42 static char meshlink_conf[PATH_MAX];
43 static char hosts_dir[PATH_MAX];
47 static char cookie[18], hash[18];
48 static char *data = NULL;
49 static size_t thedatalen = 0;
50 static bool success = false;
51 static char line[4096];
52 static char buffer[4096];
53 static size_t blen = 0;
55 //TODO: this can go away completely
56 const var_t variables[] = {
57 /* Server configuration */
58 {"AddressFamily", VAR_SERVER},
59 {"AutoConnect", VAR_SERVER | VAR_SAFE},
60 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
61 {"BindToInterface", VAR_SERVER},
62 {"Broadcast", VAR_SERVER | VAR_SAFE},
63 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
64 {"DecrementTTL", VAR_SERVER},
65 {"Device", VAR_SERVER},
66 {"DeviceType", VAR_SERVER},
67 {"DirectOnly", VAR_SERVER},
68 {"ECDSAPrivateKeyFile", VAR_SERVER},
69 {"ExperimentalProtocol", VAR_SERVER},
70 {"Forwarding", VAR_SERVER},
71 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
72 {"Hostnames", VAR_SERVER},
73 {"IffOneQueue", VAR_SERVER},
74 {"Interface", VAR_SERVER},
75 {"KeyExpire", VAR_SERVER},
76 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
77 {"LocalDiscovery", VAR_SERVER},
78 {"MACExpire", VAR_SERVER},
79 {"MaxConnectionBurst", VAR_SERVER},
80 {"MaxOutputBufferSize", VAR_SERVER},
81 {"MaxTimeout", VAR_SERVER},
82 {"Mode", VAR_SERVER | VAR_SAFE},
84 {"PingInterval", VAR_SERVER},
85 {"PingTimeout", VAR_SERVER},
86 {"PriorityInheritance", VAR_SERVER},
87 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
88 {"PrivateKeyFile", VAR_SERVER},
89 {"ProcessPriority", VAR_SERVER},
90 {"Proxy", VAR_SERVER},
91 {"ReplayWindow", VAR_SERVER},
92 {"ScriptsExtension", VAR_SERVER},
93 {"ScriptsInterpreter", VAR_SERVER},
94 {"StrictSubnets", VAR_SERVER},
95 {"TunnelServer", VAR_SERVER},
96 {"VDEGroup", VAR_SERVER},
97 {"VDEPort", VAR_SERVER},
98 /* Host configuration */
99 {"Address", VAR_HOST | VAR_MULTIPLE},
100 {"Cipher", VAR_SERVER | VAR_HOST},
101 {"ClampMSS", VAR_SERVER | VAR_HOST},
102 {"Compression", VAR_SERVER | VAR_HOST},
103 {"Digest", VAR_SERVER | VAR_HOST},
104 {"ECDSAPublicKey", VAR_HOST},
105 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
106 {"IndirectData", VAR_SERVER | VAR_HOST},
107 {"MACLength", VAR_SERVER | VAR_HOST},
108 {"PMTU", VAR_SERVER | VAR_HOST},
109 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
111 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
112 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
113 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
114 {"TCPOnly", VAR_SERVER | VAR_HOST},
115 {"Weight", VAR_HOST | VAR_SAFE},
119 static char *get_line(const char **data) {
128 static char line[1024];
129 const char *end = strchr(*data, '\n');
130 size_t len = end ? end - *data : strlen(*data);
131 if(len >= sizeof line) {
132 fprintf(stderr, "Maximum line length exceeded!\n");
135 if(len && !isprint(**data))
138 memcpy(line, *data, len);
149 static char *get_value(const char *data, const char *var) {
150 char *line = get_line(&data);
154 char *sep = line + strcspn(line, " \t=");
155 char *val = sep + strspn(sep, " \t");
157 val += 1 + strspn(val + 1, " \t");
159 if(strcasecmp(line, var))
163 static FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
164 mode_t mask = umask(0);
167 FILE *f = fopen(filename, mode);
169 if((perms & 0444) && f)
170 fchmod(fileno(f), perms);
176 static bool finalize_join(meshlink_handle_t *mesh) {
177 char *name = xstrdup(get_value(data, "Name"));
179 fprintf(stderr, "No Name found in invitation!\n");
183 if(!check_id(name)) {
184 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
188 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
189 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
193 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
194 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
198 FILE *f = fopen(meshlink_conf, "w");
200 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
204 fprintf(f, "Name = %s\n", name);
206 char filename[PATH_MAX];
207 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, name);
208 FILE *fh = fopen(filename, "w");
210 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
214 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
215 // Other chunks go unfiltered to their respective host config files
216 const char *p = data;
219 while((l = get_line(&p))) {
224 // Split line into variable and value
225 int len = strcspn(l, "\t =");
227 value += strspn(value, "\t ");
230 value += strspn(value, "\t ");
235 if(!strcasecmp(l, "Name"))
236 if(strcmp(value, name))
240 else if(!strcasecmp(l, "NetName"))
243 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
246 for(i = 0; variables[i].name; i++) {
247 if(strcasecmp(l, variables[i].name))
253 // Ignore unknown and unsafe variables
255 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
257 } else if(!(variables[i].type & VAR_SAFE)) {
258 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
262 // Copy the safe variable to the right config file
263 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
268 while(l && !strcasecmp(l, "Name")) {
269 if(!check_id(value)) {
270 fprintf(stderr, "Invalid Name found in invitation.\n");
274 if(!strcmp(value, name)) {
275 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
279 snprintf(filename,PATH_MAX, "%s" SLASH "%s", hosts_dir, value);
280 f = fopen(filename, "w");
283 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
287 while((l = get_line(&p))) {
288 if(!strcmp(l, "#---------------------------------------------------------------#"))
290 int len = strcspn(l, "\t =");
291 if(len == 4 && !strncasecmp(l, "Name", 4)) {
293 value += strspn(value, "\t ");
296 value += strspn(value, "\t ");
309 // Generate our key and send a copy to the server
310 ecdsa_t *key = ecdsa_generate();
314 char *b64key = ecdsa_get_base64_public_key(key);
318 snprintf(filename,PATH_MAX, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
319 f = fopenmask(filename, "w", 0600);
321 if(!ecdsa_write_pem_private_key(key, f)) {
322 fprintf(stderr, "Error writing private key!\n");
330 fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
332 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
339 fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
344 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
346 int result = send(sock, data, len, 0);
347 if(result == -1 && errno == EINTR)
357 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
359 case SPTPS_HANDSHAKE:
360 return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
363 data = xrealloc(data, thedatalen + len + 1);
364 memcpy(data + thedatalen, msg, len);
366 data[thedatalen] = 0;
370 return finalize_join(NULL);//TODO: wrong, we have to pass the mesh handler here, but how ?
373 fprintf(stderr, "Invitation succesfully accepted.\n");
374 shutdown(sock, SHUT_RDWR);
385 static bool recvline(int fd, char *line, size_t len) {
386 char *newline = NULL;
391 while(!(newline = memchr(buffer, '\n', blen))) {
392 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
393 if(result == -1 && errno == EINTR)
400 if(newline - buffer >= len)
403 len = newline - buffer;
405 memcpy(line, buffer, len);
407 memmove(buffer, newline + 1, blen - len - 1);
412 static bool sendline(int fd, char *format, ...) {
413 static char buffer[4096];
418 va_start(ap, format);
419 blen = vsnprintf(buffer, sizeof buffer, format, ap);
422 if(blen < 1 || blen >= sizeof buffer)
429 int result = send(fd, p, blen, MSG_NOSIGNAL);
430 if(result == -1 && errno == EINTR)
440 int rstrip(char *value) {
441 int len = strlen(value);
442 while(len && strchr("\t\r\n ", value[len - 1]))
448 static const char *errstr[] = {
449 [MESHLINK_OK] = "No error",
450 [MESHLINK_ENOMEM] = "Out of memory",
451 [MESHLINK_ENOENT] = "No such node",
454 const char *meshlink_strerror(meshlink_errno_t errno) {
455 return errstr[errno];
458 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
461 char pubname[PATH_MAX], privname[PATH_MAX];
463 fprintf(stderr, "Generating ECDSA keypair:\n");
465 if(!(key = ecdsa_generate())) {
466 fprintf(stderr, "Error during key generation!\n");
469 fprintf(stderr, "Done.\n");
471 snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
472 f = fopen(privname, "w");
478 fchmod(fileno(f), 0600);
481 if(!ecdsa_write_pem_private_key(key, f)) {
482 fprintf(stderr, "Error writing private key!\n");
491 snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
492 f = fopen(pubname, "a");
497 char *pubkey = ecdsa_get_base64_public_key(key);
498 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
507 static bool try_bind(int port) {
508 struct addrinfo *ai = NULL;
509 struct addrinfo hint = {
510 .ai_flags = AI_PASSIVE,
511 .ai_family = AF_UNSPEC,
512 .ai_socktype = SOCK_STREAM,
513 .ai_protocol = IPPROTO_TCP,
517 snprintf(portstr, sizeof portstr, "%d", port);
519 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
523 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
526 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
536 int check_port(meshlink_handle_t *mesh) {
540 fprintf(stderr, "Warning: could not bind to port 655.\n");
542 for(int i = 0; i < 100; i++) {
543 int port = 0x1000 + (rand() & 0x7fff);
545 char filename[PATH_MAX];
546 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
547 FILE *f = fopen(filename, "a");
549 fprintf(stderr, "Please change MeshLink's Port manually.\n");
553 fprintf(f, "Port = %d\n", port);
555 fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
560 fprintf(stderr, "Please change MeshLink's Port manually.\n");
564 static bool meshlink_setup(meshlink_handle_t *mesh) {
566 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
567 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
571 snprintf(hosts_dir, sizeof hosts_dir, "%s" SLASH "hosts", mesh->confbase);
573 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
574 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
578 snprintf(meshlink_conf, sizeof meshlink_conf, "%s" SLASH "meshlink.conf", mesh->confbase);
580 if(!access(meshlink_conf, F_OK)) {
581 fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
585 FILE *f = fopen(meshlink_conf, "w");
587 fprintf(stderr, "Could not create file %s: %s\n", meshlink_conf, strerror(errno));
591 fprintf(f, "Name = %s\n", mesh->name);
594 if(!ecdsa_keygen(mesh))
602 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
603 // Validate arguments provided by the application
605 if(!confbase || !*confbase) {
606 fprintf(stderr, "No confbase given!\n");
610 if(!name || !*name) {
611 fprintf(stderr, "No name given!\n");
615 if(!check_id(name)) {
616 fprintf(stderr, "Invalid name given!\n");
620 meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
621 mesh->confbase = xstrdup(confbase);
622 mesh->name = xstrdup(name);
623 event_loop_init(&mesh->loop);
624 mesh->loop.data = mesh;
626 // TODO: should be set by a function.
627 mesh->debug_level = 5;
629 // Check whether meshlink.conf already exists
631 char filename[PATH_MAX];
632 snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
634 if(access(filename, R_OK)) {
635 if(errno == ENOENT) {
637 meshlink_setup(mesh);
639 fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
640 return meshlink_close(mesh), NULL;
644 // Read the configuration
646 init_configuration(&mesh->config);
648 if(!read_server_config(mesh))
649 return meshlink_close(mesh), NULL;
651 // Setup up everything
652 // TODO: we should not open listening sockets yet
654 if(!setup_network(mesh))
655 return meshlink_close(mesh), NULL;
660 void *meshlink_main_loop(void *arg) {
661 meshlink_handle_t *mesh = arg;
663 try_outgoing_connections(mesh);
670 bool meshlink_start(meshlink_handle_t *mesh) {
671 // TODO: open listening sockets first
673 // Start the main thread
675 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
676 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
677 memset(&mesh->thread, 0, sizeof mesh->thread);
684 void meshlink_stop(meshlink_handle_t *mesh) {
685 // TODO: close the listening sockets to signal the main thread to shut down
687 // Wait for the main thread to finish
689 pthread_join(mesh->thread, NULL);
692 void meshlink_close(meshlink_handle_t *mesh) {
693 // Close and free all resources used.
695 close_network_connections(mesh);
697 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
699 exit_configuration(&mesh->config);
700 event_loop_exit(&mesh->loop);
703 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
704 mesh->receive_cb = cb;
707 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
708 mesh->node_status_cb = cb;
711 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
713 mesh->log_level = level;
716 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
718 meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
719 if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
724 packet.probe = false;
725 memset(hdr, 0, sizeof *hdr);
726 memcpy(hdr->destination, destination->name, sizeof hdr->destination);
727 memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
729 packet.len = sizeof *hdr + len;
730 memcpy(packet.data + sizeof *hdr, data, len);
732 mesh->self->in_packets++;
733 mesh->self->in_bytes += packet.len;
734 route(mesh, mesh->self, &packet);
738 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
739 return (meshlink_node_t *)lookup_node(mesh, name);
743 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
747 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
751 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
755 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
759 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
762 // Make sure confbase exists and is accessible.
763 if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
764 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
768 if(access(mesh->confbase, R_OK | W_OK | X_OK)) {
769 fprintf(stderr, "No permission to write in directory %s: %s\n", mesh->confbase, strerror(errno));
773 // TODO: Either remove or reintroduce netname in meshlink
774 // If a netname or explicit configuration directory is specified, check for an existing meshlink.conf.
775 //if((mesh->netname || confbasegiven) && !access(meshlink_conf, F_OK)) {
776 // fprintf(stderr, "Configuration file %s already exists!\n", meshlink_conf);
780 char *slash = strchr(invitation, '/');
786 if(strlen(slash) != 48)
789 char *address = invitation;
791 if(*address == '[') {
793 char *bracket = strchr(address, ']');
797 if(bracket[1] == ':')
800 port = strchr(address, ':');
805 if(!mesh->myport || !*port)
808 if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
811 // Generate a throw-away key for the invitation.
812 ecdsa_t *key = ecdsa_generate();
816 char *b64key = ecdsa_get_base64_public_key(key);
818 // Connect to the meshlink daemon mentioned in the URL.
819 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
823 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
825 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
829 if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
830 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
835 fprintf(stderr, "Connected to %s port %s...\n", address, port);
837 // Tell him we have an invitation, and give him our throw-away key.
838 int len = snprintf(invitation, sizeof invitation, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
839 if(len <= 0 || len >= sizeof invitation)
842 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
843 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
848 char hisname[4096] = "";
849 int code, hismajor, hisminor = 0;
851 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) {
852 fprintf(stderr, "Cannot read greeting from peer\n");
857 // Check if the hash of the key he gave us matches the hash in the URL.
858 char *fingerprint = line + 2;
860 if(!sha512(fingerprint, strlen(fingerprint), hishash)) {
861 fprintf(stderr, "Could not create hash\n%s\n", line + 2);
864 if(memcmp(hishash, hash, 18)) {
865 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
870 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
874 // Start an SPTPS session
875 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
878 // Feed rest of input buffer to SPTPS
879 if(!sptps_receive_data(&sptps, buffer, blen))
882 while((len = recv(sock, line, sizeof line, 0))) {
886 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
890 if(!sptps_receive_data(&sptps, line, len))
900 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
907 fprintf(stderr, "Invalid invitation URL.\n");
911 char *meshlink_export(meshlink_handle_t *mesh) {
915 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
919 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
922 static void __attribute__((constructor)) meshlink_init(void) {
926 static void __attribute__((destructor)) meshlink_exit(void) {