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"
32 /* The name this program was run with. */
33 static char *program_name = NULL;
35 /* If nonzero, display usage information and exit. */
36 static bool show_help = false;
38 /* If nonzero, print the version on standard output and exit. */
39 static bool show_version = false;
41 static char *name = NULL;
42 static char *identname = NULL; /* program name for syslog */
43 static char *pidfilename = NULL; /* pid file location */
44 static char controlcookie[1024];
46 char *confbase = NULL;
49 static struct WSAData wsa_state;
52 static struct option const long_options[] = {
53 {"config", required_argument, NULL, 'c'},
54 {"net", required_argument, NULL, 'n'},
55 {"help", no_argument, NULL, 1},
56 {"version", no_argument, NULL, 2},
57 {"pidfile", required_argument, NULL, 5},
61 static void usage(bool status) {
63 fprintf(stderr, "Try `%s --help\' for more information.\n",
66 printf("Usage: %s [options] command\n\n", program_name);
67 printf("Valid options are:\n"
68 " -c, --config=DIR Read configuration options from DIR.\n"
69 " -n, --net=NETNAME Connect to net NETNAME.\n"
70 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
71 " --help Display this help and exit.\n"
72 " --version Output version information and exit.\n"
74 "Valid commands are:\n"
75 " start Start tincd.\n"
77 " restart Restart tincd.\n"
78 " reload Reload configuration of running tincd.\n"
79 " pid Show PID of currently running tincd.\n"
80 " generate-keys [bits] Generate a new public/private keypair.\n"
81 " dump Dump a list of one of the following things:\n"
82 " nodes - all known nodes in the VPN\n"
83 " edges - all known connections in the VPN\n"
84 " subnets - all known subnets in the VPN\n"
85 " connections - all meta connections with ourself\n"
86 " graph - graph of the VPN in dotty format\n"
87 " purge Purge unreachable nodes\n"
88 " debug N Set debug level\n"
89 " retry Retry all outgoing connections\n"
90 " reload Partial reload of configuration\n"
91 " disconnect NODE Close meta connection with NODE\n"
93 " top Show real-time statistics\n"
95 " pcap Dump traffic in pcap format\n"
97 printf("Report bugs to tinc@tinc-vpn.org.\n");
101 static bool parse_options(int argc, char **argv) {
103 int option_index = 0;
105 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
107 case 0: /* long option */
110 case 'c': /* config file */
111 confbase = xstrdup(optarg);
114 case 'n': /* net name given */
115 netname = xstrdup(optarg);
118 case 1: /* show help */
122 case 2: /* show version */
126 case 5: /* open control socket here */
127 pidfilename = xstrdup(optarg);
142 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
148 /* Check stdin and stdout */
149 if(isatty(0) && isatty(1)) {
150 /* Ask for a file and/or directory name. */
151 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
155 if(fgets(buf, sizeof buf, stdin) == NULL) {
156 fprintf(stderr, "Error while reading stdin: %s\n",
161 size_t len = strlen(buf);
170 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
172 if(filename[0] != '/') {
174 /* The directory is a relative path or a filename. */
175 directory = get_current_dir_name();
176 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
180 umask(0077); /* Disallow everything for group and other */
182 /* Open it first to keep the inode busy */
184 r = fopen(filename, mode);
187 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
195 Generate a public/private RSA keypair, and ask for a file to store
198 static bool keygen(int bits) {
203 fprintf(stderr, "Generating %d bits keys:\n", bits);
205 if(!rsa_generate(&key, bits, 0x10001)) {
206 fprintf(stderr, "Error during key generation!\n");
209 fprintf(stderr, "Done.\n");
211 xasprintf(&filename, "%s/rsa_key.priv", confbase);
212 f = ask_and_open(filename, "private RSA key", "a");
218 /* Make it unreadable for others. */
219 fchmod(fileno(f), 0600);
223 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
225 rsa_write_pem_private_key(&key, f);
231 xasprintf(&filename, "%s/hosts/%s", confbase, name);
233 xasprintf(&filename, "%s/rsa_key.pub", confbase);
235 f = ask_and_open(filename, "public RSA key", "a");
241 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
243 rsa_write_pem_public_key(&key, f);
252 Set all files and paths according to netname
254 static void make_names(void) {
257 char installdir[1024] = "";
258 long len = sizeof installdir;
262 xasprintf(&identname, "tinc.%s", netname);
264 identname = xstrdup("tinc");
267 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
268 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
271 xasprintf(&confbase, "%s/%s", installdir, netname);
273 xasprintf(&confbase, "%s", installdir);
277 xasprintf(&pidfilename, "%s/pid", confbase);
285 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
289 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
291 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
294 xasprintf(&confbase, CONFDIR "/tinc");
298 static char buffer[4096];
299 static size_t blen = 0;
301 bool recvline(int fd, char *line, size_t len) {
302 char *newline = NULL;
304 while(!(newline = memchr(buffer, '\n', blen))) {
305 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
306 if(result == -1 && errno == EINTR)
313 if(newline - buffer >= len)
316 len = newline - buffer;
318 memcpy(line, buffer, len);
320 memmove(buffer, newline + 1, blen - len - 1);
326 bool recvdata(int fd, char *data, size_t len) {
328 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
329 if(result == -1 && errno == EINTR)
336 memcpy(data, buffer, len);
337 memmove(buffer, buffer + len, blen - len);
343 bool sendline(int fd, char *format, ...) {
344 static char buffer[4096];
349 va_start(ap, format);
350 blen = vsnprintf(buffer, sizeof buffer, format, ap);
353 if(blen < 0 || blen >= sizeof buffer)
360 int result = send(fd, p, blen, 0);
361 if(result == -1 && errno == EINTR)
363 else if(result <= 0);
372 void pcap(int fd, FILE *out) {
373 sendline(fd, "%d %d", CONTROL, REQ_PCAP);
381 uint32_t tz_accuracy;
401 fwrite(&header, sizeof header, 1, out);
405 while(recvline(fd, line, sizeof line)) {
407 int n = sscanf(line, "%d %d %d", &code, &req, &len);
408 gettimeofday(&tv, NULL);
409 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
411 if(!recvdata(fd, data, len))
413 packet.tv_sec = tv.tv_sec;
414 packet.tv_usec = tv.tv_usec;
416 packet.origlen = len;
417 fwrite(&packet, sizeof packet, 1, out);
418 fwrite(data, len, 1, out);
423 int main(int argc, char *argv[], char *envp[]) {
430 program_name = argv[0];
432 if(!parse_options(argc, argv))
438 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
439 VERSION, __DATE__, __TIME__, PROT_CURRENT);
440 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
441 "See the AUTHORS file for a complete list.\n\n"
442 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
443 "and you are welcome to redistribute it under certain conditions;\n"
444 "see the file COPYING for details.\n");
455 fprintf(stderr, "Not enough arguments.\n");
460 // First handle commands that don't involve connecting to a running tinc daemon.
462 if(!strcasecmp(argv[optind], "generate-keys")) {
463 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
466 if(!strcasecmp(argv[optind], "start")) {
468 execve(SBINDIR "/tincd", argv, envp);
469 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
474 * Now handle commands that do involve connecting to a running tinc daemon.
475 * Authenticate the server by ensuring the parent directory can be
476 * traversed only by root. Note this is not totally race-free unless all
477 * ancestors are writable only by trusted users, which we don't verify.
480 FILE *f = fopen(pidfilename, "r");
482 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
485 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
486 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
491 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
492 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
497 struct addrinfo hints = {
498 .ai_family = AF_UNSPEC,
499 .ai_socktype = SOCK_STREAM,
500 .ai_protocol = IPPROTO_TCP,
504 struct addrinfo *res = NULL;
506 if(getaddrinfo(host, port, &hints, &res) || !res) {
507 fprintf(stderr, "Cannot resolve %s port %s: %s", host ?: "localhost", port, strerror(errno));
511 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
513 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
518 unsigned long arg = 0;
520 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
521 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
525 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
526 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host ?: "localhost", port, sockstrerror(sockerrno));
534 int code, version, req;
536 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
537 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
538 sockstrerror(sockerrno));
542 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
544 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
545 fprintf(stderr, "Could not fully establish control socket connection\n");
549 if(!strcasecmp(argv[optind], "pid")) {
554 if(!strcasecmp(argv[optind], "stop")) {
555 sendline(fd, "%d %d", CONTROL, REQ_STOP);
556 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
557 fprintf(stderr, "Could not stop tinc daemon\n");
563 if(!strcasecmp(argv[optind], "reload")) {
564 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
565 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
566 fprintf(stderr, "Could not reload tinc daemon\n");
572 if(!strcasecmp(argv[optind], "restart")) {
573 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
574 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
575 fprintf(stderr, "Could not restart tinc daemon\n");
581 if(!strcasecmp(argv[optind], "retry")) {
582 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
583 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
584 fprintf(stderr, "Could not retry outgoing connections\n");
590 if(!strcasecmp(argv[optind], "dump")) {
591 if(argc < optind + 2) {
592 fprintf(stderr, "Not enough arguments.\n");
597 bool do_graph = false;
599 if(!strcasecmp(argv[optind+1], "nodes"))
600 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
601 else if(!strcasecmp(argv[optind+1], "edges"))
602 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
603 else if(!strcasecmp(argv[optind+1], "subnets"))
604 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
605 else if(!strcasecmp(argv[optind+1], "connections"))
606 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
607 else if(!strcasecmp(argv[optind+1], "graph")) {
608 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
609 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
611 printf("digraph {\n");
613 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
618 while(recvline(fd, line, sizeof line)) {
619 char node1[4096], node2[4096];
620 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
622 if(do_graph && req == REQ_DUMP_NODES)
634 printf("%s\n", line + 5);
636 if(req == REQ_DUMP_NODES)
637 printf(" %s [label = \"%s\"];\n", node1, node1);
639 printf(" %s -> %s;\n", node1, node2);
643 fprintf(stderr, "Error receiving dump\n");
647 if(!strcasecmp(argv[optind], "purge")) {
648 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
649 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
650 fprintf(stderr, "Could not purge tinc daemon\n");
656 if(!strcasecmp(argv[optind], "debug")) {
657 int debuglevel, origlevel;
659 if(argc != optind + 2) {
660 fprintf(stderr, "Invalid arguments.\n");
663 debuglevel = atoi(argv[optind+1]);
665 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
666 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
667 fprintf(stderr, "Could not purge tinc daemon\n");
671 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
675 if(!strcasecmp(argv[optind], "connect")) {
676 if(argc != optind + 2) {
677 fprintf(stderr, "Invalid arguments.\n");
680 char *name = argv[optind + 1];
682 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
683 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
684 fprintf(stderr, "Could not connect to %s\n", name);
690 if(!strcasecmp(argv[optind], "disconnect")) {
691 if(argc != optind + 2) {
692 fprintf(stderr, "Invalid arguments.\n");
695 char *name = argv[optind + 1];
697 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
698 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
699 fprintf(stderr, "Could not disconnect %s\n", name);
706 if(!strcasecmp(argv[optind], "top")) {
712 if(!strcasecmp(argv[optind], "pcap")) {
717 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);