2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2011 Guus Sliepen <guus@tinc-vpn.org>
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.
26 #include "control_common.h"
33 /* The name this program was run with. */
34 static char *program_name = NULL;
36 /* If nonzero, display usage information and exit. */
37 static bool show_help = false;
39 /* If nonzero, print the version on standard output and exit. */
40 static bool show_version = false;
42 static char *name = NULL;
43 static char *identname = NULL; /* program name for syslog */
44 static char *pidfilename = NULL; /* pid file location */
45 static char controlcookie[1024];
47 char *confbase = NULL;
50 static struct WSAData wsa_state;
53 static struct option const long_options[] = {
54 {"config", required_argument, NULL, 'c'},
55 {"net", required_argument, NULL, 'n'},
56 {"help", no_argument, NULL, 1},
57 {"version", no_argument, NULL, 2},
58 {"pidfile", required_argument, NULL, 5},
62 static void usage(bool status) {
64 fprintf(stderr, "Try `%s --help\' for more information.\n",
67 printf("Usage: %s [options] command\n\n", program_name);
68 printf("Valid options are:\n"
69 " -c, --config=DIR Read configuration options from DIR.\n"
70 " -n, --net=NETNAME Connect to net NETNAME.\n"
71 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
72 " --help Display this help and exit.\n"
73 " --version Output version information and exit.\n"
75 "Valid commands are:\n"
76 " start Start tincd.\n"
78 " restart Restart tincd.\n"
79 " reload Reload configuration of running tincd.\n"
80 " pid Show PID of currently running tincd.\n"
81 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
82 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
83 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
84 " dump Dump a list of one of the following things:\n"
85 " nodes - all known nodes in the VPN\n"
86 " edges - all known connections in the VPN\n"
87 " subnets - all known subnets in the VPN\n"
88 " connections - all meta connections with ourself\n"
89 " graph - graph of the VPN in dotty format\n"
90 " purge Purge unreachable nodes\n"
91 " debug N Set debug level\n"
92 " retry Retry all outgoing connections\n"
93 " reload Partial reload of configuration\n"
94 " disconnect NODE Close meta connection with NODE\n"
96 " top Show real-time statistics\n"
98 " pcap Dump traffic in pcap format\n"
100 printf("Report bugs to tinc@tinc-vpn.org.\n");
104 static bool parse_options(int argc, char **argv) {
106 int option_index = 0;
108 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
110 case 0: /* long option */
113 case 'c': /* config file */
114 confbase = xstrdup(optarg);
117 case 'n': /* net name given */
118 netname = xstrdup(optarg);
121 case 1: /* show help */
125 case 2: /* show version */
129 case 5: /* open control socket here */
130 pidfilename = xstrdup(optarg);
145 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
151 /* Check stdin and stdout */
152 if(isatty(0) && isatty(1)) {
153 /* Ask for a file and/or directory name. */
154 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
158 if(fgets(buf, sizeof buf, stdin) == NULL) {
159 fprintf(stderr, "Error while reading stdin: %s\n",
164 size_t len = strlen(buf);
173 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
175 if(filename[0] != '/') {
177 /* The directory is a relative path or a filename. */
178 directory = get_current_dir_name();
179 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
183 umask(0077); /* Disallow everything for group and other */
185 /* Open it first to keep the inode busy */
187 r = fopen(filename, mode);
190 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
198 Generate a public/private ECDSA keypair, and ask for a file to store
201 static bool ecdsa_keygen() {
206 fprintf(stderr, "Generating ECDSA keypair:\n");
208 if(!ecdsa_generate(&key)) {
209 fprintf(stderr, "Error during key generation!\n");
212 fprintf(stderr, "Done.\n");
214 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
215 f = ask_and_open(filename, "private ECDSA key", "a");
221 /* Make it unreadable for others. */
222 fchmod(fileno(f), 0600);
226 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
228 ecdsa_write_pem_private_key(&key, f);
234 xasprintf(&filename, "%s/hosts/%s", confbase, name);
236 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
238 f = ask_and_open(filename, "public ECDSA key", "a");
244 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
246 char *pubkey = ecdsa_get_base64_public_key(&key);
247 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
257 Generate a public/private RSA keypair, and ask for a file to store
260 static bool rsa_keygen(int bits) {
265 fprintf(stderr, "Generating %d bits keys:\n", bits);
267 if(!rsa_generate(&key, bits, 0x10001)) {
268 fprintf(stderr, "Error during key generation!\n");
271 fprintf(stderr, "Done.\n");
273 xasprintf(&filename, "%s/rsa_key.priv", confbase);
274 f = ask_and_open(filename, "private RSA key", "a");
280 /* Make it unreadable for others. */
281 fchmod(fileno(f), 0600);
285 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
287 rsa_write_pem_private_key(&key, f);
293 xasprintf(&filename, "%s/hosts/%s", confbase, name);
295 xasprintf(&filename, "%s/rsa_key.pub", confbase);
297 f = ask_and_open(filename, "public RSA key", "a");
303 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
305 rsa_write_pem_public_key(&key, f);
314 Set all files and paths according to netname
316 static void make_names(void) {
319 char installdir[1024] = "";
320 long len = sizeof installdir;
324 xasprintf(&identname, "tinc.%s", netname);
326 identname = xstrdup("tinc");
329 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
330 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
333 xasprintf(&confbase, "%s/%s", installdir, netname);
335 xasprintf(&confbase, "%s", installdir);
339 xasprintf(&pidfilename, "%s/pid", confbase);
347 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
351 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
353 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
356 xasprintf(&confbase, CONFDIR "/tinc");
360 static char buffer[4096];
361 static size_t blen = 0;
363 bool recvline(int fd, char *line, size_t len) {
364 char *newline = NULL;
366 while(!(newline = memchr(buffer, '\n', blen))) {
367 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
368 if(result == -1 && errno == EINTR)
375 if(newline - buffer >= len)
378 len = newline - buffer;
380 memcpy(line, buffer, len);
382 memmove(buffer, newline + 1, blen - len - 1);
388 bool recvdata(int fd, char *data, size_t len) {
390 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
391 if(result == -1 && errno == EINTR)
398 memcpy(data, buffer, len);
399 memmove(buffer, buffer + len, blen - len);
405 bool sendline(int fd, char *format, ...) {
406 static char buffer[4096];
411 va_start(ap, format);
412 blen = vsnprintf(buffer, sizeof buffer, format, ap);
415 if(blen < 0 || blen >= sizeof buffer)
422 int result = send(fd, p, blen, 0);
423 if(result == -1 && errno == EINTR)
425 else if(result <= 0);
434 void pcap(int fd, FILE *out) {
435 sendline(fd, "%d %d", CONTROL, REQ_PCAP);
443 uint32_t tz_accuracy;
463 fwrite(&header, sizeof header, 1, out);
467 while(recvline(fd, line, sizeof line)) {
469 int n = sscanf(line, "%d %d %d", &code, &req, &len);
470 gettimeofday(&tv, NULL);
471 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
473 if(!recvdata(fd, data, len))
475 packet.tv_sec = tv.tv_sec;
476 packet.tv_usec = tv.tv_usec;
478 packet.origlen = len;
479 fwrite(&packet, sizeof packet, 1, out);
480 fwrite(data, len, 1, out);
485 int main(int argc, char *argv[], char *envp[]) {
492 program_name = argv[0];
494 if(!parse_options(argc, argv))
500 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
501 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
502 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
503 "See the AUTHORS file for a complete list.\n\n"
504 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
505 "and you are welcome to redistribute it under certain conditions;\n"
506 "see the file COPYING for details.\n");
517 fprintf(stderr, "Not enough arguments.\n");
522 // First handle commands that don't involve connecting to a running tinc daemon.
524 if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
525 return !rsa_keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
528 if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
529 return !ecdsa_keygen();
532 if(!strcasecmp(argv[optind], "generate-keys")) {
533 return !(rsa_keygen(optind > argc ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
536 if(!strcasecmp(argv[optind], "start")) {
538 execve(SBINDIR "/tincd", argv, envp);
539 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
544 * Now handle commands that do involve connecting to a running tinc daemon.
545 * Authenticate the server by ensuring the parent directory can be
546 * traversed only by root. Note this is not totally race-free unless all
547 * ancestors are writable only by trusted users, which we don't verify.
550 FILE *f = fopen(pidfilename, "r");
552 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
555 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
556 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
561 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
562 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
567 struct addrinfo hints = {
568 .ai_family = AF_UNSPEC,
569 .ai_socktype = SOCK_STREAM,
570 .ai_protocol = IPPROTO_TCP,
574 struct addrinfo *res = NULL;
576 if(getaddrinfo(host, port, &hints, &res) || !res) {
577 fprintf(stderr, "Cannot resolve %s port %s: %s", host ?: "localhost", port, strerror(errno));
581 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
583 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
588 unsigned long arg = 0;
590 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
591 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
595 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
596 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host ?: "localhost", port, sockstrerror(sockerrno));
604 int code, version, req;
606 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
607 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
608 sockstrerror(sockerrno));
612 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
614 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
615 fprintf(stderr, "Could not fully establish control socket connection\n");
619 if(!strcasecmp(argv[optind], "pid")) {
624 if(!strcasecmp(argv[optind], "stop")) {
625 sendline(fd, "%d %d", CONTROL, REQ_STOP);
626 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
627 fprintf(stderr, "Could not stop tinc daemon\n");
633 if(!strcasecmp(argv[optind], "reload")) {
634 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
635 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
636 fprintf(stderr, "Could not reload tinc daemon\n");
642 if(!strcasecmp(argv[optind], "restart")) {
643 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
644 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
645 fprintf(stderr, "Could not restart tinc daemon\n");
651 if(!strcasecmp(argv[optind], "retry")) {
652 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
653 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
654 fprintf(stderr, "Could not retry outgoing connections\n");
660 if(!strcasecmp(argv[optind], "dump")) {
661 if(argc < optind + 2) {
662 fprintf(stderr, "Not enough arguments.\n");
667 bool do_graph = false;
669 if(!strcasecmp(argv[optind+1], "nodes"))
670 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
671 else if(!strcasecmp(argv[optind+1], "edges"))
672 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
673 else if(!strcasecmp(argv[optind+1], "subnets"))
674 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
675 else if(!strcasecmp(argv[optind+1], "connections"))
676 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
677 else if(!strcasecmp(argv[optind+1], "graph")) {
678 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
679 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
681 printf("digraph {\n");
683 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
688 while(recvline(fd, line, sizeof line)) {
689 char node1[4096], node2[4096];
690 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
692 if(do_graph && req == REQ_DUMP_NODES)
704 printf("%s\n", line + 5);
706 if(req == REQ_DUMP_NODES)
707 printf(" %s [label = \"%s\"];\n", node1, node1);
709 printf(" %s -> %s;\n", node1, node2);
713 fprintf(stderr, "Error receiving dump\n");
717 if(!strcasecmp(argv[optind], "purge")) {
718 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
719 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
720 fprintf(stderr, "Could not purge tinc daemon\n");
726 if(!strcasecmp(argv[optind], "debug")) {
727 int debuglevel, origlevel;
729 if(argc != optind + 2) {
730 fprintf(stderr, "Invalid arguments.\n");
733 debuglevel = atoi(argv[optind+1]);
735 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
736 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
737 fprintf(stderr, "Could not purge tinc daemon\n");
741 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
745 if(!strcasecmp(argv[optind], "connect")) {
746 if(argc != optind + 2) {
747 fprintf(stderr, "Invalid arguments.\n");
750 char *name = argv[optind + 1];
752 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
753 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
754 fprintf(stderr, "Could not connect to %s\n", name);
760 if(!strcasecmp(argv[optind], "disconnect")) {
761 if(argc != optind + 2) {
762 fprintf(stderr, "Invalid arguments.\n");
765 char *name = argv[optind + 1];
767 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
768 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
769 fprintf(stderr, "Could not disconnect %s\n", name);
776 if(!strcasecmp(argv[optind], "top")) {
782 if(!strcasecmp(argv[optind], "pcap")) {
787 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);