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"
23 char *hosts_dir = NULL;
24 static char *name = NULL;
25 char *tinc_conf = NULL;
26 static bool tty = false;
28 /* Open a file with the desired permissions, minus the umask.
29 Also, if we want to create an executable file, we call fchmod()
30 to set the executable bits. */
32 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
33 mode_t mask = umask(0);
36 FILE *f = fopen(filename, mode);
38 if((perms & 0444) && f)
39 fchmod(fileno(f), perms);
45 static void disable_old_keys(const char *filename, const char *what) {
46 char tmpfile[PATH_MAX] = "";
48 bool disabled = false;
53 r = fopen(filename, "r");
57 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
59 struct stat st = {.st_mode = 0600};
60 fstat(fileno(r), &st);
61 w = fopenmask(tmpfile, "w", st.st_mode);
63 while(fgets(buf, sizeof buf, r)) {
64 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
65 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
71 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
77 if(block || ecdsapubkey)
79 if(fputs(buf, w) < 0) {
85 if(block && !strncmp(buf, "-----END ", 9))
92 if(ferror(r) || fclose(r) < 0)
97 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
104 // We cannot atomically replace files on Windows.
105 char bakfile[PATH_MAX] = "";
106 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
107 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
108 rename(bakfile, filename);
110 if(rename(tmpfile, filename)) {
112 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
117 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
124 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
130 /* Check stdin and stdout */
132 /* Ask for a file and/or directory name. */
133 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
135 if(fgets(buf, sizeof buf, stdin) == NULL) {
136 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
140 size_t len = strlen(buf);
149 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
151 if(filename[0] != '/') {
153 /* The directory is a relative path or a filename. */
154 directory = get_current_dir_name();
155 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
159 disable_old_keys(filename, what);
161 /* Open it first to keep the inode busy */
163 r = fopenmask(filename, mode, perms);
166 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
174 Generate a public/private ECDSA keypair, and ask for a file to store
177 bool ecdsa_keygen(bool ask) {
180 char *pubname, *privname;
182 fprintf(stderr, "Generating ECDSA keypair:\n");
184 if(!(key = ecdsa_generate())) {
185 fprintf(stderr, "Error during key generation!\n");
188 fprintf(stderr, "Done.\n");
190 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
191 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
197 if(!ecdsa_write_pem_private_key(key, f)) {
198 fprintf(stderr, "Error writing private key!\n");
207 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
209 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
211 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
217 char *pubkey = ecdsa_get_base64_public_key(key);
218 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
228 Generate a public/private RSA keypair, and ask for a file to store
231 bool rsa_keygen(int bits, bool ask) {
234 char *pubname, *privname;
236 fprintf(stderr, "Generating %d bits keys:\n", bits);
238 if(!(key = rsa_generate(bits, 0x10001))) {
239 fprintf(stderr, "Error during key generation!\n");
242 fprintf(stderr, "Done.\n");
244 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
245 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
251 if(!rsa_write_pem_private_key(key, f)) {
252 fprintf(stderr, "Error writing private key!\n");
261 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
263 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
265 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
271 if(!rsa_write_pem_public_key(key, f)) {
272 fprintf(stderr, "Error writing public key!\n");
284 static bool try_bind(int port) {
285 struct addrinfo *ai = NULL;
286 struct addrinfo hint = {
287 .ai_flags = AI_PASSIVE,
288 .ai_family = AF_UNSPEC,
289 .ai_socktype = SOCK_STREAM,
290 .ai_protocol = IPPROTO_TCP,
294 snprintf(portstr, sizeof portstr, "%d", port);
296 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
300 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
303 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
313 int check_port(char *name) {
317 fprintf(stderr, "Warning: could not bind to port 655. ");
319 for(int i = 0; i < 100; i++) {
320 int port = 0x1000 + (rand() & 0x7fff);
323 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
324 FILE *f = fopen(filename, "a");
327 fprintf(stderr, "Please change tinc's Port manually.\n");
331 fprintf(f, "Port = %d\n", port);
333 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
338 fprintf(stderr, "Please change tinc's Port manually.\n");
341 //tinc_setup() should basically do what cmd_init() from src/tincctl.c does, except it doesn't have to generate a tinc-up script.
342 bool tinc_setup(const char* confbaseapi, const char* name) {
343 confbase = confbaseapi;
345 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
346 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
347 if(!access(tinc_conf, F_OK)) {
348 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
352 if(!check_id(name)) {
353 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
357 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
358 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
362 if(mkdir(confbase, 0777) && errno != EEXIST) {
363 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
367 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
368 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
372 FILE *f = fopen(tinc_conf, "w");
374 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
378 fprintf(f, "Name = %s\n", name);
381 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
391 bool tinc_start(const char* confbaseapi) {
392 pthread_t tincThread;
393 confbase = confbaseapi;
394 pthread_create(&tincThread,NULL,tinc_main_thread,confbaseapi);
395 pthread_detach(tincThread);
399 bool tinc_main_thread(void * in) {
401 confbase = (char*) in;
402 printf("Hello World %s\n",confbase);
408 // can be called from any thread
409 bool tinc_send_packet(node_t *receiver, const char* buf, unsigned int len);
411 // handler runs in tinc thread and should return immediately
412 bool tinc_set_packet_receive_handler(void (*handler)(const char* sender, const char* buf, unsigned int len));
415 //It might also be a good idea to add the option of looking up hosts by public
416 //key (fingerprints) instead of names.
418 node_t *tinc_get_host(const char *name);
420 bool tinc_get_hosts(node_t** hosts);
422 bool tinc_sign(const char* payload, unsigned int len, const char** signature);
424 int tinc_verify(const char* sender, const char* payload, unsigned int plen, const char* signature, unsigned int slen);
427 TODO: It would be good to add a void pointer here that will be passed on to the
428 handler function whenever it is called, or have a void pointer in node_t
429 that can be filled in by the application. That way, you can easily link an
430 application-specific data structure to a node_t.
432 void channel_set_packet_send_handler(int (*handler)(const char* receiver, const char* buf, unsigned int len));
433 void channel_packet_receive_handler(const char* sender, const char* buf, unsigned int len);
435 bool channel_open(const char* partner, void(*read)(int id, const char* buf, unsigned int len), void(*result)(int result, int id));
436 void channel_close(int id);
437 bool channel_write(int id, const char* buf, unsigned int len, void(*result)(int result, int id, unsigned int written));
440 //We do need some more functions. First of all, we need to be able to add nodes
441 //to a VPN. To do that, either an invitation protocol should be used:
443 bool tinc_join_network(const char *invitation);
444 const char *tinc_generate_invitation(const char *name);
447 Or two nodes should exchange some information (their name, address, public
448 key). If the application provides a way to exchange some data with another
452 bool tinc_export(char *buf, size_t *len);
453 node_t *tinc_import(const char *buf, size_t len);
455 Last but not least, some way to get rid of unwanted nodes. Simplest is a
456 function that just blacklists a node.
457 Which should immediately cause the local tincd to ignore any data from that
458 host from that point on. Of course, a somewhat centrally managed,
459 automatically distributed blacklist or whitelist would be the next step.
461 bool tinc_blacklist(node_t *host);