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;
71 /* Open a file with the desired permissions, minus the umask.
72 Also, if we want to create an executable file, we call fchmod()
73 to set the executable bits. */
75 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
76 mode_t mask = umask(0);
79 FILE *f = fopen(filename, mode);
81 if((perms & 0444) && f)
82 fchmod(fileno(f), perms);
88 static void disable_old_keys(const char *filename, const char *what) {
89 char tmpfile[PATH_MAX] = "";
91 bool disabled = false;
96 r = fopen(filename, "r");
100 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
102 struct stat st = {.st_mode = 0600};
103 fstat(fileno(r), &st);
104 w = fopenmask(tmpfile, "w", st.st_mode);
106 while(fgets(buf, sizeof buf, r)) {
107 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
108 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
114 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
120 if(block || ecdsapubkey)
122 if(fputs(buf, w) < 0) {
128 if(block && !strncmp(buf, "-----END ", 9))
135 if(ferror(r) || fclose(r) < 0)
140 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
147 // We cannot atomically replace files on Windows.
148 char bakfile[PATH_MAX] = "";
149 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
150 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
151 rename(bakfile, filename);
153 if(rename(tmpfile, filename)) {
155 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
160 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
167 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
173 /* Check stdin and stdout */
175 /* Ask for a file and/or directory name. */
176 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
178 if(fgets(buf, sizeof buf, stdin) == NULL) {
179 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
183 size_t len = strlen(buf);
192 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
194 if(filename[0] != '/') {
196 /* The directory is a relative path or a filename. */
197 directory = get_current_dir_name();
198 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
202 disable_old_keys(filename, what);
204 /* Open it first to keep the inode busy */
206 r = fopenmask(filename, mode, perms);
209 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
217 Generate a public/private ECDSA keypair, and ask for a file to store
220 bool ecdsa_keygen(bool ask) {
223 char *pubname, *privname;
225 fprintf(stderr, "Generating ECDSA keypair:\n");
227 if(!(key = ecdsa_generate())) {
228 fprintf(stderr, "Error during key generation!\n");
231 fprintf(stderr, "Done.\n");
233 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
234 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
240 if(!ecdsa_write_pem_private_key(key, f)) {
241 fprintf(stderr, "Error writing private key!\n");
250 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
252 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
254 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
260 char *pubkey = ecdsa_get_base64_public_key(key);
261 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
271 Generate a public/private RSA keypair, and ask for a file to store
274 bool rsa_keygen(int bits, bool ask) {
277 char *pubname, *privname;
279 fprintf(stderr, "Generating %d bits keys:\n", bits);
281 if(!(key = rsa_generate(bits, 0x10001))) {
282 fprintf(stderr, "Error during key generation!\n");
285 fprintf(stderr, "Done.\n");
287 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
288 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
294 if(!rsa_write_pem_private_key(key, f)) {
295 fprintf(stderr, "Error writing private key!\n");
304 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
306 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
308 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
314 if(!rsa_write_pem_public_key(key, f)) {
315 fprintf(stderr, "Error writing public key!\n");
327 static bool try_bind(int port) {
328 struct addrinfo *ai = NULL;
329 struct addrinfo hint = {
330 .ai_flags = AI_PASSIVE,
331 .ai_family = AF_UNSPEC,
332 .ai_socktype = SOCK_STREAM,
333 .ai_protocol = IPPROTO_TCP,
337 snprintf(portstr, sizeof portstr, "%d", port);
339 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
343 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
346 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
356 int check_port(char *name) {
360 fprintf(stderr, "Warning: could not bind to port 655. ");
362 for(int i = 0; i < 100; i++) {
363 int port = 0x1000 + (rand() & 0x7fff);
366 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
367 FILE *f = fopen(filename, "a");
370 fprintf(stderr, "Please change tinc's Port manually.\n");
374 fprintf(f, "Port = %d\n", port);
376 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
381 fprintf(stderr, "Please change tinc's Port manually.\n");
384 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
385 bool tinc_setup(const char* confbaseapi, const char* name) {
386 confbase = confbaseapi;
388 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
389 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
390 if(!access(tinc_conf, F_OK)) {
391 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
395 if(!check_id(name)) {
396 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
400 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
401 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
405 if(mkdir(confbase, 0777) && errno != EEXIST) {
406 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
410 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
411 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
415 FILE *f = fopen(tinc_conf, "w");
417 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
421 fprintf(f, "Name = %s\n", name);
424 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
434 bool tinc_start(const char* confbaseapi) {
435 pthread_t tincThread;
436 confbase = confbaseapi;
437 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
438 pthread_detach(tincThread);
442 bool tinc_main_thread(void * in) {
444 static bool status = false;
446 /* If nonzero, write log entries to a separate file. */
447 bool use_logfile = false;
449 confbase = (char*) in;
451 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
453 init_configuration(&config_tree);
455 /* Slllluuuuuuurrrrp! */
457 gettimeofday(&now, NULL);
458 srand(now.tv_sec + now.tv_usec);
461 if(!read_server_config())
465 if(lzo_init() != LZO_E_OK) {
466 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
471 //char *priority = NULL; //shoud be not needed in libmeshlink
474 /* Lock all pages into memory if requested.
475 * This has to be done after daemon()/fork() so it works for child.
476 * No need to do that in parent as it's very short-lived. */
477 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
478 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
484 /* Setup sockets and open device. */
486 if(!setup_meshlink_network())
489 /* Change process priority */
490 //should be not needed in libmeshlink
491 //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
492 // if(!strcasecmp(priority, "Normal")) {
493 // if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
494 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
497 // } else if(!strcasecmp(priority, "Low")) {
498 // if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
499 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
502 // } else if(!strcasecmp(priority, "High")) {
503 // if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
504 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
508 // logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
513 /* drop privileges */
517 /* Start main loop. It only exits when tinc is killed. */
519 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
521 try_outgoing_connections();
523 status = main_loop();
525 /* Shutdown properly. */
528 close_network_connections();
530 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
536 exit_configuration(&config_tree);
546 bool route_meshlink(node_t *source,vpn_packet_t *packet) {
548 printf("data %s\n",packet->data);
549 printf("data 11%s\n",packet->data+11);
550 printf("data 32%s\n",packet->data+32);
551 node_t* owner = NULL;
553 tincpackethdr* hdr = (tincpackethdr*)packet->data;
554 owner = lookup_node(hdr->destination);
561 printf("lookupnode %s\n",owner->name);
563 if(!owner->status.reachable) {
568 //TODO: I skipped here a lot of checks !
570 send_packet(owner,packet);
573 // can be called from any thread
574 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
577 tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
579 if (sizeof(hdr) + len > MAXSIZE) {
585 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
586 memcpy(hdr->source,myself->name,sizeof(hdr->source));
590 memcpy(packet.data,hdr,32);
591 memcpy(packet.data+32,buf,len);
593 myself->in_packets++;
594 myself->in_bytes += packet.len;
595 route_meshlink(myself, &packet);
600 // handler runs in tinc thread and should return immediately
601 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
604 //It might also be a good idea to add the option of looking up hosts by public
605 //key (fingerprints) instead of names.
607 node_t *tinc_get_host(const char *name) {
613 bool tinc_get_hosts(node_t** hosts);
615 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
617 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
620 TODO: It would be good to add a void pointer here that will be passed on to the
621 handler function whenever it is called, or have a void pointer in node_t
622 that can be filled in by the application. That way, you can easily link an
623 application-specific data structure to a node_t.
625 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
626 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
628 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
629 void channel_close(int id);
630 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
633 //We do need some more functions. First of all, we need to be able to add nodes
634 //to a VPN. To do that, either an invitation protocol should be used:
636 bool tinc_join_network(const char *invitation);
637 const char *tinc_generate_invitation(const char *name);
640 Or two nodes should exchange some information (their name, address, public
641 key). If the application provides a way to exchange some data with another
645 bool tinc_export(char *buf, size_t *len);
646 node_t *tinc_import(const char *buf, size_t len);
648 Last but not least, some way to get rid of unwanted nodes. Simplest is a
649 function that just blacklists a node.
650 Which should immediately cause the local tincd to ignore any data from that
651 host from that point on. Of course, a somewhat centrally managed,
652 automatically distributed blacklist or whitelist would be the next step.
654 bool tinc_blacklist(node_t *host);