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);
266 static bool try_bind(int port) {
267 struct addrinfo *ai = NULL;
268 struct addrinfo hint = {
269 .ai_flags = AI_PASSIVE,
270 .ai_family = AF_UNSPEC,
271 .ai_socktype = SOCK_STREAM,
272 .ai_protocol = IPPROTO_TCP,
276 snprintf(portstr, sizeof portstr, "%d", port);
278 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
282 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
285 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
295 int check_port(char *name) {
299 fprintf(stderr, "Warning: could not bind to port 655. ");
301 for(int i = 0; i < 100; i++) {
302 int port = 0x1000 + (rand() & 0x7fff);
305 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
306 FILE *f = fopen(filename, "a");
309 fprintf(stderr, "Please change tinc's Port manually.\n");
313 fprintf(f, "Port = %d\n", port);
315 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
320 fprintf(stderr, "Please change tinc's Port manually.\n");
323 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
324 bool tinc_setup(const char* confbaseapi, const char* name) {
325 confbase = xstrdup(confbaseapi);
326 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
327 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
328 if(!access(tinc_conf, F_OK)) {
329 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
333 if(!check_id(name)) {
334 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
338 if(mkdir(confbase, 0777) && errno != EEXIST) {
339 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
343 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
344 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
348 FILE *f = fopen(tinc_conf, "w");
350 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
354 fprintf(f, "Name = %s\n", name);
357 if(!ecdsa_keygen(false))
367 bool tinc_start(const char* confbaseapi) {
368 pthread_t tincThread;
369 confbase = confbaseapi;
370 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
371 pthread_detach(tincThread);
375 bool tinc_main_thread(void * in) {
376 static bool status = false;
378 /* If nonzero, write log entries to a separate file. */
379 bool use_logfile = false;
381 confbase = (char*) in;
383 openlogger("tinc", LOGMODE_STDERR);
385 init_configuration(&config_tree);
387 /* Slllluuuuuuurrrrp! */
389 gettimeofday(&now, NULL);
390 srand(now.tv_sec + now.tv_usec);
393 if(!read_server_config())
396 //char *priority = NULL; //shoud be not needed in libmeshlink
399 /* Lock all pages into memory if requested.
400 * This has to be done after daemon()/fork() so it works for child.
401 * No need to do that in parent as it's very short-lived. */
402 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
403 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
409 /* Setup sockets and open device. */
411 if(!setup_meshlink_network())
414 /* Change process priority */
415 //should be not needed in libmeshlink
416 //if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
417 // if(!strcasecmp(priority, "Normal")) {
418 // if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
419 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
422 // } else if(!strcasecmp(priority, "Low")) {
423 // if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
424 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
427 // } else if(!strcasecmp(priority, "High")) {
428 // if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
429 // logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
433 // logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
438 /* drop privileges */
442 /* Start main loop. It only exits when tinc is killed. */
444 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
446 try_outgoing_connections();
448 status = main_loop();
450 /* Shutdown properly. */
453 close_network_connections();
455 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
461 exit_configuration(&config_tree);
469 // can be called from any thread
470 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
473 tincpackethdr* hdr = malloc(sizeof(tincpackethdr));
474 if (sizeof(tincpackethdr) + len > MAXSIZE) {
480 memset(hdr->legacymtu,1,sizeof(hdr->legacymtu));
481 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
482 memcpy(hdr->source,myself->name,sizeof(hdr->source));
485 packet.len = sizeof(tincpackethdr) + len;
487 memcpy(packet.data,hdr,sizeof(tincpackethdr));
488 memcpy(packet.data+sizeof(tincpackethdr),buf,len);
490 myself->in_packets++;
491 myself->in_bytes += packet.len;
492 route(myself, &packet);
497 // handler runs in tinc thread and should return immediately
498 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
501 //It might also be a good idea to add the option of looking up hosts by public
502 //key (fingerprints) instead of names.
504 node_t *tinc_get_host(const char *name) {
510 bool tinc_get_hosts(node_t** hosts);
512 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
514 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
517 TODO: It would be good to add a void pointer here that will be passed on to the
518 handler function whenever it is called, or have a void pointer in node_t
519 that can be filled in by the application. That way, you can easily link an
520 application-specific data structure to a node_t.
522 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
523 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
525 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
526 void channel_close(int id);
527 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
530 //We do need some more functions. First of all, we need to be able to add nodes
531 //to a VPN. To do that, either an invitation protocol should be used:
533 bool tinc_join_network(const char *invitation);
534 const char *tinc_generate_invitation(const char *name);
537 Or two nodes should exchange some information (their name, address, public
538 key). If the application provides a way to exchange some data with another
542 bool tinc_export(char *buf, size_t *len);
543 node_t *tinc_import(const char *buf, size_t len);
545 Last but not least, some way to get rid of unwanted nodes. Simplest is a
546 function that just blacklists a node.
547 Which should immediately cause the local tincd to ignore any data from that
548 host from that point on. Of course, a somewhat centrally managed,
549 automatically distributed blacklist or whitelist would be the next step.
551 bool tinc_blacklist(node_t *host);