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.
24 #include "connection.h"
28 #include "libmeshlink.h"
33 char *hosts_dir = NULL;
34 recvdata_cb_t recv_callback;
35 static char *name = NULL;
36 char *tinc_conf = NULL;
37 static bool tty = false;
40 /* If nonzero, disable swapping for this process. */
41 static bool do_mlock = false;
44 /* Open a file with the desired permissions, minus the umask.
45 Also, if we want to create an executable file, we call fchmod()
46 to set the executable bits. */
48 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
49 mode_t mask = umask(0);
52 FILE *f = fopen(filename, mode);
54 if((perms & 0444) && f)
55 fchmod(fileno(f), perms);
61 static void disable_old_keys(const char *filename, const char *what) {
62 char tmpfile[PATH_MAX] = "";
64 bool disabled = false;
69 r = fopen(filename, "r");
73 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
75 struct stat st = {.st_mode = 0600};
76 fstat(fileno(r), &st);
77 w = fopenmask(tmpfile, "w", st.st_mode);
79 while(fgets(buf, sizeof buf, r)) {
80 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
81 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
87 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
93 if(block || ecdsapubkey)
95 if(fputs(buf, w) < 0) {
101 if(block && !strncmp(buf, "-----END ", 9))
108 if(ferror(r) || fclose(r) < 0)
113 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
120 // We cannot atomically replace files on Windows.
121 char bakfile[PATH_MAX] = "";
122 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
123 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
124 rename(bakfile, filename);
126 if(rename(tmpfile, filename)) {
128 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
133 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
140 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
146 /* Check stdin and stdout */
148 /* Ask for a file and/or directory name. */
149 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
151 if(fgets(buf, sizeof buf, stdin) == NULL) {
152 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
156 size_t len = strlen(buf);
165 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
167 if(filename[0] != '/') {
169 /* The directory is a relative path or a filename. */
170 directory = get_current_dir_name();
171 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
175 disable_old_keys(filename, what);
177 /* Open it first to keep the inode busy */
179 r = fopenmask(filename, mode, perms);
182 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
190 Generate a public/private ECDSA keypair, and ask for a file to store
193 bool ecdsa_keygen(bool ask) {
196 char *pubname, *privname;
198 fprintf(stderr, "Generating ECDSA keypair:\n");
200 if(!(key = ecdsa_generate())) {
201 fprintf(stderr, "Error during key generation!\n");
204 fprintf(stderr, "Done.\n");
206 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
207 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
213 if(!ecdsa_write_pem_private_key(key, f)) {
214 fprintf(stderr, "Error writing private key!\n");
223 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
225 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
227 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
233 char *pubkey = ecdsa_get_base64_public_key(key);
234 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
243 static bool try_bind(int port) {
244 struct addrinfo *ai = NULL;
245 struct addrinfo hint = {
246 .ai_flags = AI_PASSIVE,
247 .ai_family = AF_UNSPEC,
248 .ai_socktype = SOCK_STREAM,
249 .ai_protocol = IPPROTO_TCP,
253 snprintf(portstr, sizeof portstr, "%d", port);
255 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
259 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
262 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
272 int check_port(const char *name) {
276 fprintf(stderr, "Warning: could not bind to port 655. ");
278 for(int i = 0; i < 100; i++) {
279 int port = 0x1000 + (rand() & 0x7fff);
282 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
283 FILE *f = fopen(filename, "a");
286 fprintf(stderr, "Please change tinc's Port manually.\n");
290 fprintf(f, "Port = %d\n", port);
292 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
297 fprintf(stderr, "Please change tinc's Port manually.\n");
300 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
301 bool tinc_setup(const char* confbaseapi, const char* name) {
302 confbase = xstrdup(confbaseapi);
303 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
304 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
305 if(!access(tinc_conf, F_OK)) {
306 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
310 if(!check_id(name)) {
311 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
315 if(mkdir(confbase, 0777) && errno != EEXIST) {
316 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
320 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
321 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
325 FILE *f = fopen(tinc_conf, "w");
327 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
331 fprintf(f, "Name = %s\n", name);
334 if(!ecdsa_keygen(false))
344 bool tinc_start(const char* confbaseapi) {
345 pthread_t tincThread;
346 confbase = xstrdup(confbaseapi);
347 pthread_create(&tincThread,NULL,tinc_main_thread,confbase);
348 pthread_detach(tincThread);
352 __attribute__((constructor)) static void meshlink_init(void) {
353 /* Slllluuuuuuurrrrp! */
355 gettimeofday(&now, NULL);
356 srand(now.tv_sec + now.tv_usec);
360 __attribute__((destructor)) static void meshlink_exit(void) {
365 void *tinc_main_thread(void * in) {
366 static bool status = false;
367 /* If nonzero, write log entries to a separate file. */
368 bool use_logfile = false;
370 confbase = (char*) in;
372 openlogger("tinc", LOGMODE_STDERR);
374 init_configuration(&config_tree);
376 if(!read_server_config())
379 //char *priority = NULL; //shoud be not needed in libmeshlink
381 /* Setup sockets and open device. */
386 /* Start main loop. It only exits when tinc is killed. */
388 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
390 try_outgoing_connections();
392 status = main_loop();
394 /* Shutdown properly. */
397 close_network_connections();
399 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
403 exit_configuration(&config_tree);
405 return (void *)status;
410 // can be called from any thread
411 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len) {
414 tincpackethdr* hdr = (tincpackethdr *)packet.data;
415 if (sizeof(tincpackethdr) + len > MAXSIZE) {
421 packet.probe = false;
422 memset(hdr, 0, sizeof *hdr);
423 memcpy(hdr->destination,receiver->name,sizeof(hdr->destination));
424 memcpy(hdr->source,myself->name,sizeof(hdr->source));
426 packet.len = sizeof(tincpackethdr) + len;
427 memcpy(packet.data+sizeof(tincpackethdr),buf,len);
429 myself->in_packets++;
430 myself->in_bytes += packet.len;
431 route(myself, &packet);
436 // handler runs in tinc thread and should return immediately
437 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
440 //It might also be a good idea to add the option of looking up hosts by public
441 //key (fingerprints) instead of names.
443 node_t *tinc_get_host(const char *name) {
449 bool tinc_get_hosts(node_t** hosts);
451 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
453 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
456 TODO: It would be good to add a void pointer here that will be passed on to the
457 handler function whenever it is called, or have a void pointer in node_t
458 that can be filled in by the application. That way, you can easily link an
459 application-specific data structure to a node_t.
461 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
462 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
464 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
465 void channel_close(int id);
466 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
469 //We do need some more functions. First of all, we need to be able to add nodes
470 //to a VPN. To do that, either an invitation protocol should be used:
472 bool tinc_join_network(const char *invitation);
473 const char *tinc_generate_invitation(const char *name);
476 Or two nodes should exchange some information (their name, address, public
477 key). If the application provides a way to exchange some data with another
481 bool tinc_export(char *buf, size_t *len);
482 node_t *tinc_import(const char *buf, size_t len);
484 Last but not least, some way to get rid of unwanted nodes. Simplest is a
485 function that just blacklists a node.
486 Which should immediately cause the local tincd to ignore any data from that
487 host from that point on. Of course, a somewhat centrally managed,
488 automatically distributed blacklist or whitelist would be the next step.
490 bool tinc_blacklist(node_t *host);
492 void recvdata_register_cb(recvdata_cb_t cb) {