2 libmeshlink.h -- Tincd Library
3 Copyright (C) 2014 Guus Sliepen <guus@tinc-vpn.org> 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"
22 #ifdef HAVE_SYS_MMAN_H
27 char *hosts_dir = NULL;
28 static char *name = NULL;
29 char *tinc_conf = NULL;
30 static bool tty = false;
33 /* If nonzero, disable swapping for this process. */
34 static bool do_mlock = false;
40 bool setup_meshlink_network(void) {
47 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
48 if(pinginterval < 1) {
54 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
56 if(pingtimeout < 1 || pingtimeout > pinginterval)
57 pingtimeout = pinginterval;
59 //TODO: check if this makes sense in libmeshlink
60 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
61 maxoutbufsize = 10 * MTU;
69 /* Run subnet-up scripts for our own subnets */
71 subnet_update(myself, NULL, true);
76 /* Open a file with the desired permissions, minus the umask.
77 Also, if we want to create an executable file, we call fchmod()
78 to set the executable bits. */
80 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
81 mode_t mask = umask(0);
84 FILE *f = fopen(filename, mode);
86 if((perms & 0444) && f)
87 fchmod(fileno(f), perms);
93 static void disable_old_keys(const char *filename, const char *what) {
94 char tmpfile[PATH_MAX] = "";
96 bool disabled = false;
101 r = fopen(filename, "r");
105 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
107 struct stat st = {.st_mode = 0600};
108 fstat(fileno(r), &st);
109 w = fopenmask(tmpfile, "w", st.st_mode);
111 while(fgets(buf, sizeof buf, r)) {
112 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
113 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
119 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
125 if(block || ecdsapubkey)
127 if(fputs(buf, w) < 0) {
133 if(block && !strncmp(buf, "-----END ", 9))
140 if(ferror(r) || fclose(r) < 0)
145 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
152 // We cannot atomically replace files on Windows.
153 char bakfile[PATH_MAX] = "";
154 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
155 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
156 rename(bakfile, filename);
158 if(rename(tmpfile, filename)) {
160 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
165 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
172 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
178 /* Check stdin and stdout */
180 /* Ask for a file and/or directory name. */
181 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
183 if(fgets(buf, sizeof buf, stdin) == NULL) {
184 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
188 size_t len = strlen(buf);
197 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
199 if(filename[0] != '/') {
201 /* The directory is a relative path or a filename. */
202 directory = get_current_dir_name();
203 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
207 disable_old_keys(filename, what);
209 /* Open it first to keep the inode busy */
211 r = fopenmask(filename, mode, perms);
214 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
222 Generate a public/private ECDSA keypair, and ask for a file to store
225 bool ecdsa_keygen(bool ask) {
228 char *pubname, *privname;
230 fprintf(stderr, "Generating ECDSA keypair:\n");
232 if(!(key = ecdsa_generate())) {
233 fprintf(stderr, "Error during key generation!\n");
236 fprintf(stderr, "Done.\n");
238 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
239 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
245 if(!ecdsa_write_pem_private_key(key, f)) {
246 fprintf(stderr, "Error writing private key!\n");
255 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
257 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
259 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
265 char *pubkey = ecdsa_get_base64_public_key(key);
266 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
276 Generate a public/private RSA keypair, and ask for a file to store
279 bool rsa_keygen(int bits, bool ask) {
282 char *pubname, *privname;
284 fprintf(stderr, "Generating %d bits keys:\n", bits);
286 if(!(key = rsa_generate(bits, 0x10001))) {
287 fprintf(stderr, "Error during key generation!\n");
290 fprintf(stderr, "Done.\n");
292 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
293 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
299 if(!rsa_write_pem_private_key(key, f)) {
300 fprintf(stderr, "Error writing private key!\n");
309 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
311 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
313 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
319 if(!rsa_write_pem_public_key(key, f)) {
320 fprintf(stderr, "Error writing public key!\n");
332 static bool try_bind(int port) {
333 struct addrinfo *ai = NULL;
334 struct addrinfo hint = {
335 .ai_flags = AI_PASSIVE,
336 .ai_family = AF_UNSPEC,
337 .ai_socktype = SOCK_STREAM,
338 .ai_protocol = IPPROTO_TCP,
342 snprintf(portstr, sizeof portstr, "%d", port);
344 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
348 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
351 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
361 int check_port(char *name) {
365 fprintf(stderr, "Warning: could not bind to port 655. ");
367 for(int i = 0; i < 100; i++) {
368 int port = 0x1000 + (rand() & 0x7fff);
371 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
372 FILE *f = fopen(filename, "a");
375 fprintf(stderr, "Please change tinc's Port manually.\n");
379 fprintf(f, "Port = %d\n", port);
381 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
386 fprintf(stderr, "Please change tinc's Port manually.\n");
389 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
390 bool tinc_setup(const char* confbaseapi, const char* name) {
391 confbase = confbaseapi;
393 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
394 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
395 if(!access(tinc_conf, F_OK)) {
396 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
400 if(!check_id(name)) {
401 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
405 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
406 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
410 if(mkdir(confbase, 0777) && errno != EEXIST) {
411 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
415 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
416 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
420 FILE *f = fopen(tinc_conf, "w");
422 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
426 fprintf(f, "Name = %s\n", name);
429 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
439 bool tinc_start(const char* confbaseapi) {
440 pthread_t tincThread;
441 confbase = confbaseapi;
442 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
443 pthread_detach(tincThread);
447 bool tinc_main_thread(void * in) {
449 static bool status = false;
451 /* If nonzero, write log entries to a separate file. */
452 bool use_logfile = false;
454 confbase = (char*) in;
456 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
458 init_configuration(&config_tree);
460 /* Slllluuuuuuurrrrp! */
462 gettimeofday(&now, NULL);
463 srand(now.tv_sec + now.tv_usec);
466 if(!read_server_config())
470 if(lzo_init() != LZO_E_OK) {
471 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
476 //char *priority = NULL; //shoud be not needed in libmeshlink
479 /* Lock all pages into memory if requested.
480 * This has to be done after daemon()/fork() so it works for child.
481 * No need to do that in parent as it's very short-lived. */
482 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
483 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
489 /* Setup sockets and open device. */
491 if(!setup_meshlink_network())
494 /* Change process priority */
495 //should be not needed in libmeshlink
496 //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
497 // if(!strcasecmp(priority, "Normal")) {
498 // if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
499 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
502 // } else if(!strcasecmp(priority, "Low")) {
503 // if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
504 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
507 // } else if(!strcasecmp(priority, "High")) {
508 // if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
509 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
513 // logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
518 /* drop privileges */
522 /* Start main loop. It only exits when tinc is killed. */
524 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
526 try_outgoing_connections();
528 status = main_loop();
530 /* Shutdown properly. */
533 close_network_connections();
535 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
541 exit_configuration(&config_tree);
551 bool route_meshlink(node_t *source,vpn_packet_t *packet) {
553 printf("data %s\n",packet->data);
554 printf("data 11%s\n",packet->data+11);
555 printf("data 32%s\n",packet->data+32);
556 node_t* owner = NULL;
558 tincpackethdr* hdr = (tincpackethdr*)packet->data;
559 owner = lookup_node(hdr->destination);
566 printf("lookupnode %s\n",owner->name);
568 if(!owner->status.reachable) {
573 //TODO: I skipped here a lot of checks !
575 send_packet(owner,packet);
578 // can be called from any thread
579 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
582 tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
584 if (sizeof(hdr) + len > MAXSIZE) {
590 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
591 memcpy(hdr->source,myself->name,sizeof(hdr->source));
595 memcpy(packet.data,hdr,32);
596 memcpy(packet.data+32,buf,len);
598 myself->in_packets++;
599 myself->in_bytes += packet.len;
600 route_meshlink(myself, &packet);
605 // handler runs in tinc thread and should return immediately
606 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
609 //It might also be a good idea to add the option of looking up hosts by public
610 //key (fingerprints) instead of names.
612 node_t *tinc_get_host(const char *name) {
618 bool tinc_get_hosts(node_t** hosts);
620 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
622 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
625 TODO: It would be good to add a void pointer here that will be passed on to the
626 handler function whenever it is called, or have a void pointer in node_t
627 that can be filled in by the application. That way, you can easily link an
628 application-specific data structure to a node_t.
630 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
631 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
633 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
634 void channel_close(int id);
635 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
638 //We do need some more functions. First of all, we need to be able to add nodes
639 //to a VPN. To do that, either an invitation protocol should be used:
641 bool tinc_join_network(const char *invitation);
642 const char *tinc_generate_invitation(const char *name);
645 Or two nodes should exchange some information (their name, address, public
646 key). If the application provides a way to exchange some data with another
650 bool tinc_export(char *buf, size_t *len);
651 node_t *tinc_import(const char *buf, size_t len);
653 Last but not least, some way to get rid of unwanted nodes. Simplest is a
654 function that just blacklists a node.
655 Which should immediately cause the local tincd to ignore any data from that
656 host from that point on. Of course, a somewhat centrally managed,
657 automatically distributed blacklist or whitelist would be the next step.
659 bool tinc_blacklist(node_t *host);