2 libmeshlink.h -- Tincd Library
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io> Saverio Proto <zioproto@gmail.com>
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.
20 #include "libmeshlink.h"
21 #ifdef HAVE_SYS_MMAN_H
26 char *hosts_dir = NULL;
27 static char *name = NULL;
28 char *tinc_conf = NULL;
29 static bool tty = false;
32 /* If nonzero, disable swapping for this process. */
33 static bool do_mlock = false;
39 bool setup_meshlink_network(void) {
45 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
46 if(pinginterval < 1) {
52 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
54 if(pingtimeout < 1 || pingtimeout > pinginterval)
55 pingtimeout = pinginterval;
57 //TODO: check if this makes sense in libmeshlink
58 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
59 maxoutbufsize = 10 * MTU;
67 /* Open a file with the desired permissions, minus the umask.
68 Also, if we want to create an executable file, we call fchmod()
69 to set the executable bits. */
71 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
72 mode_t mask = umask(0);
75 FILE *f = fopen(filename, mode);
77 if((perms & 0444) && f)
78 fchmod(fileno(f), perms);
84 static void disable_old_keys(const char *filename, const char *what) {
85 char tmpfile[PATH_MAX] = "";
87 bool disabled = false;
92 r = fopen(filename, "r");
96 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
98 struct stat st = {.st_mode = 0600};
99 fstat(fileno(r), &st);
100 w = fopenmask(tmpfile, "w", st.st_mode);
102 while(fgets(buf, sizeof buf, r)) {
103 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
104 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
110 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
116 if(block || ecdsapubkey)
118 if(fputs(buf, w) < 0) {
124 if(block && !strncmp(buf, "-----END ", 9))
131 if(ferror(r) || fclose(r) < 0)
136 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
143 // We cannot atomically replace files on Windows.
144 char bakfile[PATH_MAX] = "";
145 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
146 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
147 rename(bakfile, filename);
149 if(rename(tmpfile, filename)) {
151 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
156 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
163 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
169 /* Check stdin and stdout */
171 /* Ask for a file and/or directory name. */
172 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
174 if(fgets(buf, sizeof buf, stdin) == NULL) {
175 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
179 size_t len = strlen(buf);
188 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
190 if(filename[0] != '/') {
192 /* The directory is a relative path or a filename. */
193 directory = get_current_dir_name();
194 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
198 disable_old_keys(filename, what);
200 /* Open it first to keep the inode busy */
202 r = fopenmask(filename, mode, perms);
205 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
213 Generate a public/private ECDSA keypair, and ask for a file to store
216 bool ecdsa_keygen(bool ask) {
219 char *pubname, *privname;
221 fprintf(stderr, "Generating ECDSA keypair:\n");
223 if(!(key = ecdsa_generate())) {
224 fprintf(stderr, "Error during key generation!\n");
227 fprintf(stderr, "Done.\n");
229 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
230 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
236 if(!ecdsa_write_pem_private_key(key, f)) {
237 fprintf(stderr, "Error writing private key!\n");
246 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
248 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
250 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
256 char *pubkey = ecdsa_get_base64_public_key(key);
257 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
267 Generate a public/private RSA keypair, and ask for a file to store
270 bool rsa_keygen(int bits, bool ask) {
273 char *pubname, *privname;
275 fprintf(stderr, "Generating %d bits keys:\n", bits);
277 if(!(key = rsa_generate(bits, 0x10001))) {
278 fprintf(stderr, "Error during key generation!\n");
281 fprintf(stderr, "Done.\n");
283 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
284 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
290 if(!rsa_write_pem_private_key(key, f)) {
291 fprintf(stderr, "Error writing private key!\n");
300 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
302 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
304 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
310 if(!rsa_write_pem_public_key(key, f)) {
311 fprintf(stderr, "Error writing public key!\n");
323 static bool try_bind(int port) {
324 struct addrinfo *ai = NULL;
325 struct addrinfo hint = {
326 .ai_flags = AI_PASSIVE,
327 .ai_family = AF_UNSPEC,
328 .ai_socktype = SOCK_STREAM,
329 .ai_protocol = IPPROTO_TCP,
333 snprintf(portstr, sizeof portstr, "%d", port);
335 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
339 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
342 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
352 int check_port(char *name) {
356 fprintf(stderr, "Warning: could not bind to port 655. ");
358 for(int i = 0; i < 100; i++) {
359 int port = 0x1000 + (rand() & 0x7fff);
362 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
363 FILE *f = fopen(filename, "a");
366 fprintf(stderr, "Please change tinc's Port manually.\n");
370 fprintf(f, "Port = %d\n", port);
372 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
377 fprintf(stderr, "Please change tinc's Port manually.\n");
380 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
381 bool tinc_setup(const char* confbaseapi, const char* name) {
382 confbase = xstrdup(confbaseapi);
383 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
384 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
385 if(!access(tinc_conf, F_OK)) {
386 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
390 if(!check_id(name)) {
391 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
395 if(mkdir(confbase, 0777) && errno != EEXIST) {
396 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
400 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
401 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
405 FILE *f = fopen(tinc_conf, "w");
407 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
411 fprintf(f, "Name = %s\n", name);
414 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
424 bool tinc_start(const char* confbaseapi) {
425 pthread_t tincThread;
426 confbase = confbaseapi;
427 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
428 pthread_detach(tincThread);
432 bool tinc_main_thread(void * in) {
433 static bool status = false;
435 /* If nonzero, write log entries to a separate file. */
436 bool use_logfile = false;
438 confbase = (char*) in;
440 openlogger("tinc", LOGMODE_STDERR);
442 init_configuration(&config_tree);
444 /* Slllluuuuuuurrrrp! */
446 gettimeofday(&now, NULL);
447 srand(now.tv_sec + now.tv_usec);
450 if(!read_server_config())
453 //char *priority = NULL; //shoud be not needed in libmeshlink
456 /* Lock all pages into memory if requested.
457 * This has to be done after daemon()/fork() so it works for child.
458 * No need to do that in parent as it's very short-lived. */
459 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
460 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
466 /* Setup sockets and open device. */
468 if(!setup_meshlink_network())
471 /* Change process priority */
472 //should be not needed in libmeshlink
473 //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
474 // if(!strcasecmp(priority, "Normal")) {
475 // if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
476 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
479 // } else if(!strcasecmp(priority, "Low")) {
480 // if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
481 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
484 // } else if(!strcasecmp(priority, "High")) {
485 // if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
486 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
490 // logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
495 /* drop privileges */
499 /* Start main loop. It only exits when tinc is killed. */
501 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
503 try_outgoing_connections();
505 status = main_loop();
507 /* Shutdown properly. */
510 close_network_connections();
512 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
518 exit_configuration(&config_tree);
526 bool route_meshlink(node_t *source,vpn_packet_t *packet) {
528 printf("data %s\n",packet->data);
529 printf("data 16%s\n",packet->data+16);
530 printf("data 32%s\n",packet->data+32);
531 node_t* owner = NULL;
533 tincpackethdr* hdr = (tincpackethdr*)packet->data;
534 owner = lookup_node(hdr->destination);
541 printf("lookupnode %s\n",owner->name);
543 if(!owner->status.reachable) {
548 //TODO: I skipped here a lot of checks !
550 send_packet(owner,packet);
553 // can be called from any thread
554 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
557 tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
559 if (sizeof(hdr) + len > MAXSIZE) {
565 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
566 memcpy(hdr->source,myself->name,sizeof(hdr->source));
569 packet.len = len + 32;
571 memcpy(packet.data,hdr,32);
572 memcpy(packet.data+32,buf,len);
574 myself->in_packets++;
575 myself->in_bytes += packet.len;
576 route_meshlink(myself, &packet);
581 // handler runs in tinc thread and should return immediately
582 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
585 //It might also be a good idea to add the option of looking up hosts by public
586 //key (fingerprints) instead of names.
588 node_t *tinc_get_host(const char *name) {
594 bool tinc_get_hosts(node_t** hosts);
596 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
598 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
601 TODO: It would be good to add a void pointer here that will be passed on to the
602 handler function whenever it is called, or have a void pointer in node_t
603 that can be filled in by the application. That way, you can easily link an
604 application-specific data structure to a node_t.
606 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
607 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
609 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
610 void channel_close(int id);
611 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
614 //We do need some more functions. First of all, we need to be able to add nodes
615 //to a VPN. To do that, either an invitation protocol should be used:
617 bool tinc_join_network(const char *invitation);
618 const char *tinc_generate_invitation(const char *name);
621 Or two nodes should exchange some information (their name, address, public
622 key). If the application provides a way to exchange some data with another
626 bool tinc_export(char *buf, size_t *len);
627 node_t *tinc_import(const char *buf, size_t len);
629 Last but not least, some way to get rid of unwanted nodes. Simplest is a
630 function that just blacklists a node.
631 Which should immediately cause the local tincd to ignore any data from that
632 host from that point on. Of course, a somewhat centrally managed,
633 automatically distributed blacklist or whitelist would be the next step.
635 bool tinc_blacklist(node_t *host);