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) {
46 if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
47 if(pinginterval < 1) {
53 if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
55 if(pingtimeout < 1 || pingtimeout > pinginterval)
56 pingtimeout = pinginterval;
58 //TODO: check if this makes sense in libmeshlink
59 if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
60 maxoutbufsize = 10 * MTU;
68 /* Open a file with the desired permissions, minus the umask.
69 Also, if we want to create an executable file, we call fchmod()
70 to set the executable bits. */
72 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
73 mode_t mask = umask(0);
76 FILE *f = fopen(filename, mode);
78 if((perms & 0444) && f)
79 fchmod(fileno(f), perms);
85 static void disable_old_keys(const char *filename, const char *what) {
86 char tmpfile[PATH_MAX] = "";
88 bool disabled = false;
93 r = fopen(filename, "r");
97 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
99 struct stat st = {.st_mode = 0600};
100 fstat(fileno(r), &st);
101 w = fopenmask(tmpfile, "w", st.st_mode);
103 while(fgets(buf, sizeof buf, r)) {
104 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
105 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
111 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
117 if(block || ecdsapubkey)
119 if(fputs(buf, w) < 0) {
125 if(block && !strncmp(buf, "-----END ", 9))
132 if(ferror(r) || fclose(r) < 0)
137 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
144 // We cannot atomically replace files on Windows.
145 char bakfile[PATH_MAX] = "";
146 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
147 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
148 rename(bakfile, filename);
150 if(rename(tmpfile, filename)) {
152 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
157 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
164 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
170 /* Check stdin and stdout */
172 /* Ask for a file and/or directory name. */
173 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
175 if(fgets(buf, sizeof buf, stdin) == NULL) {
176 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
180 size_t len = strlen(buf);
189 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
191 if(filename[0] != '/') {
193 /* The directory is a relative path or a filename. */
194 directory = get_current_dir_name();
195 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
199 disable_old_keys(filename, what);
201 /* Open it first to keep the inode busy */
203 r = fopenmask(filename, mode, perms);
206 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
214 Generate a public/private ECDSA keypair, and ask for a file to store
217 bool ecdsa_keygen(bool ask) {
220 char *pubname, *privname;
222 fprintf(stderr, "Generating ECDSA keypair:\n");
224 if(!(key = ecdsa_generate())) {
225 fprintf(stderr, "Error during key generation!\n");
228 fprintf(stderr, "Done.\n");
230 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
231 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
237 if(!ecdsa_write_pem_private_key(key, f)) {
238 fprintf(stderr, "Error writing private key!\n");
247 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
249 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
251 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
257 char *pubkey = ecdsa_get_base64_public_key(key);
258 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
268 Generate a public/private RSA keypair, and ask for a file to store
271 bool rsa_keygen(int bits, bool ask) {
274 char *pubname, *privname;
276 fprintf(stderr, "Generating %d bits keys:\n", bits);
278 if(!(key = rsa_generate(bits, 0x10001))) {
279 fprintf(stderr, "Error during key generation!\n");
282 fprintf(stderr, "Done.\n");
284 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
285 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
291 if(!rsa_write_pem_private_key(key, f)) {
292 fprintf(stderr, "Error writing private key!\n");
301 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
303 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
305 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
311 if(!rsa_write_pem_public_key(key, f)) {
312 fprintf(stderr, "Error writing public key!\n");
324 static bool try_bind(int port) {
325 struct addrinfo *ai = NULL;
326 struct addrinfo hint = {
327 .ai_flags = AI_PASSIVE,
328 .ai_family = AF_UNSPEC,
329 .ai_socktype = SOCK_STREAM,
330 .ai_protocol = IPPROTO_TCP,
334 snprintf(portstr, sizeof portstr, "%d", port);
336 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
340 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
343 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
353 int check_port(char *name) {
357 fprintf(stderr, "Warning: could not bind to port 655. ");
359 for(int i = 0; i < 100; i++) {
360 int port = 0x1000 + (rand() & 0x7fff);
363 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
364 FILE *f = fopen(filename, "a");
367 fprintf(stderr, "Please change tinc's Port manually.\n");
371 fprintf(f, "Port = %d\n", port);
373 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
378 fprintf(stderr, "Please change tinc's Port manually.\n");
381 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
382 bool tinc_setup(const char* confbaseapi, const char* name) {
383 confbase = xstrdup(confbaseapi);
384 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
385 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
386 if(!access(tinc_conf, F_OK)) {
387 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
391 if(!check_id(name)) {
392 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
396 if(mkdir(confbase, 0777) && errno != EEXIST) {
397 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
401 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
402 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
406 FILE *f = fopen(tinc_conf, "w");
408 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
412 fprintf(f, "Name = %s\n", name);
415 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
425 bool tinc_start(const char* confbaseapi) {
426 pthread_t tincThread;
427 confbase = confbaseapi;
428 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
429 pthread_detach(tincThread);
433 bool tinc_main_thread(void * in) {
434 static bool status = false;
436 /* If nonzero, write log entries to a separate file. */
437 bool use_logfile = false;
439 confbase = (char*) in;
441 openlogger("tinc", LOGMODE_STDERR);
443 init_configuration(&config_tree);
445 /* Slllluuuuuuurrrrp! */
447 gettimeofday(&now, NULL);
448 srand(now.tv_sec + now.tv_usec);
451 if(!read_server_config())
455 if(lzo_init() != LZO_E_OK) {
456 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
461 //char *priority = NULL; //shoud be not needed in libmeshlink
464 /* Lock all pages into memory if requested.
465 * This has to be done after daemon()/fork() so it works for child.
466 * No need to do that in parent as it's very short-lived. */
467 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
468 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
474 /* Setup sockets and open device. */
476 if(!setup_meshlink_network())
479 /* Change process priority */
480 //should be not needed in libmeshlink
481 //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
482 // if(!strcasecmp(priority, "Normal")) {
483 // if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
484 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
487 // } else if(!strcasecmp(priority, "Low")) {
488 // if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
489 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
492 // } else if(!strcasecmp(priority, "High")) {
493 // if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
494 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
498 // logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
503 /* drop privileges */
507 /* Start main loop. It only exits when tinc is killed. */
509 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
511 try_outgoing_connections();
513 status = main_loop();
515 /* Shutdown properly. */
518 close_network_connections();
520 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
526 exit_configuration(&config_tree);
535 bool route_meshlink(node_t *source,vpn_packet_t *packet) {
537 printf("data %s\n",packet->data);
538 printf("data 11%s\n",packet->data+11);
539 printf("data 32%s\n",packet->data+32);
540 node_t* owner = NULL;
542 tincpackethdr* hdr = (tincpackethdr*)packet->data;
543 owner = lookup_node(hdr->destination);
550 printf("lookupnode %s\n",owner->name);
552 if(!owner->status.reachable) {
557 //TODO: I skipped here a lot of checks !
559 send_packet(owner,packet);
562 // can be called from any thread
563 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
566 tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
568 if (sizeof(hdr) + len > MAXSIZE) {
574 memset(hdr->legacymtu,0,sizeof(hdr->legacymtu));
575 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
576 memcpy(hdr->source,myself->name,sizeof(hdr->source));
579 packet.len = sizeof(tincpackethdr) + len;
581 memcpy(packet.data,hdr,32+14);
582 memcpy(packet.data+32+14,buf,len);
584 myself->in_packets++;
585 myself->in_bytes += packet.len;
586 route_meshlink(myself, &packet);
591 // handler runs in tinc thread and should return immediately
592 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
595 //It might also be a good idea to add the option of looking up hosts by public
596 //key (fingerprints) instead of names.
598 node_t *tinc_get_host(const char *name) {
604 bool tinc_get_hosts(node_t** hosts);
606 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
608 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
611 TODO: It would be good to add a void pointer here that will be passed on to the
612 handler function whenever it is called, or have a void pointer in node_t
613 that can be filled in by the application. That way, you can easily link an
614 application-specific data structure to a node_t.
616 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
617 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
619 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
620 void channel_close(int id);
621 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
624 //We do need some more functions. First of all, we need to be able to add nodes
625 //to a VPN. To do that, either an invitation protocol should be used:
627 bool tinc_join_network(const char *invitation);
628 const char *tinc_generate_invitation(const char *name);
631 Or two nodes should exchange some information (their name, address, public
632 key). If the application provides a way to exchange some data with another
636 bool tinc_export(char *buf, size_t *len);
637 node_t *tinc_import(const char *buf, size_t len);
639 Last but not least, some way to get rid of unwanted nodes. Simplest is a
640 function that just blacklists a node.
641 Which should immediately cause the local tincd to ignore any data from that
642 host from that point on. Of course, a somewhat centrally managed,
643 automatically distributed blacklist or whitelist would be the next step.
645 bool tinc_blacklist(node_t *host);