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 /* If nonzero, it will attempt to kill a running tincd and exit. */
42 static int kill_tincd = 0;
44 /* If nonzero, generate public/private keypair for this host/net. */
45 static int generate_keys = 0;
47 static char *name = NULL;
48 static char *identname = NULL; /* program name for syslog */
49 static char *controlcookiename = NULL; /* cookie file location */
50 static char controlcookie[1024];
52 char *confbase = NULL;
53 static char *host = NULL;
56 static struct WSAData wsa_state;
59 static struct option const long_options[] = {
60 {"config", required_argument, NULL, 'c'},
61 {"host", required_argument, NULL, 'h'},
62 {"net", required_argument, NULL, 'n'},
63 {"help", no_argument, NULL, 1},
64 {"version", no_argument, NULL, 2},
65 {"controlcookie", required_argument, NULL, 5},
69 static void usage(bool status) {
71 fprintf(stderr, "Try `%s --help\' for more information.\n",
74 printf("Usage: %s [options] command\n\n", program_name);
75 printf("Valid options are:\n"
76 " -c, --config=DIR Read configuration options from DIR.\n"
77 " -n, --net=NETNAME Connect to net NETNAME.\n"
78 " --controlcookie=FILENAME Read control socket from FILENAME.\n"
79 " --help Display this help and exit.\n"
80 " --version Output version information and exit.\n"
82 "Valid commands are:\n"
83 " start Start tincd.\n"
85 " restart Restart tincd.\n"
86 " reload Reload configuration of running tincd.\n"
87 " pid Show PID of currently running tincd.\n"
88 " generate-keys [bits] Generate a new public/private keypair.\n"
89 " dump Dump a list of one of the following things:\n"
90 " nodes - all known nodes in the VPN\n"
91 " edges - all known connections in the VPN\n"
92 " subnets - all known subnets in the VPN\n"
93 " connections - all meta connections with ourself\n"
94 " graph - graph of the VPN in dotty format\n"
95 " purge Purge unreachable nodes\n"
96 " debug N Set debug level\n"
97 " retry Retry all outgoing connections\n"
98 " reload Partial reload of configuration\n"
99 " disconnect NODE Close meta connection with NODE\n"
101 " top Show real-time statistics\n"
103 " pcap Dump traffic in pcap format\n"
105 printf("Report bugs to tinc@tinc-vpn.org.\n");
109 static bool parse_options(int argc, char **argv) {
111 int option_index = 0;
113 while((r = getopt_long(argc, argv, "c:n:h:", long_options, &option_index)) != EOF) {
115 case 0: /* long option */
118 case 'c': /* config file */
119 confbase = xstrdup(optarg);
122 case 'h': /* alternative host to connect to */
123 host = xstrdup(optarg);
126 case 'n': /* net name given */
127 netname = xstrdup(optarg);
130 case 1: /* show help */
134 case 2: /* show version */
138 case 5: /* open control socket here */
139 controlcookiename = xstrdup(optarg);
154 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
161 /* Check stdin and stdout */
162 if(isatty(0) && isatty(1)) {
163 /* Ask for a file and/or directory name. */
164 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
168 if(fgets(buf, sizeof buf, stdin) == NULL) {
169 fprintf(stderr, "Error while reading stdin: %s\n",
183 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
185 if(filename[0] != '/') {
187 /* The directory is a relative path or a filename. */
188 directory = get_current_dir_name();
189 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
193 umask(0077); /* Disallow everything for group and other */
195 /* Open it first to keep the inode busy */
197 r = fopen(filename, mode);
200 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
208 Generate a public/private RSA keypair, and ask for a file to store
211 static bool keygen(int bits) {
216 fprintf(stderr, "Generating %d bits keys:\n", bits);
218 if(!rsa_generate(&key, bits, 0x10001)) {
219 fprintf(stderr, "Error during key generation!\n");
222 fprintf(stderr, "Done.\n");
224 xasprintf(&filename, "%s/rsa_key.priv", confbase);
225 f = ask_and_open(filename, "private RSA key", "a");
231 /* Make it unreadable for others. */
232 fchmod(fileno(f), 0600);
236 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
238 rsa_write_pem_private_key(&key, f);
244 xasprintf(&filename, "%s/hosts/%s", confbase, name);
246 xasprintf(&filename, "%s/rsa_key.pub", confbase);
248 f = ask_and_open(filename, "public RSA key", "a");
254 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
256 rsa_write_pem_public_key(&key, f);
265 Set all files and paths according to netname
267 static void make_names(void) {
270 char installdir[1024] = "";
271 long len = sizeof installdir;
275 xasprintf(&identname, "tinc.%s", netname);
277 identname = xstrdup("tinc");
280 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
281 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
284 xasprintf(&confbase, "%s/%s", installdir, netname);
286 xasprintf(&confbase, "%s", installdir);
289 if(!controlcookiename)
290 xasprintf(&controlcookiename, "%s/cookie", confbase);
297 if(!controlcookiename)
298 xasprintf(&controlcookiename, "%s/run/%s.cookie", LOCALSTATEDIR, identname);
302 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
304 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
307 xasprintf(&confbase, CONFDIR "/tinc");
311 static char buffer[4096];
312 static size_t blen = 0;
314 bool recvline(int fd, char *line, size_t len) {
315 char *newline = NULL;
317 while(!(newline = memchr(buffer, '\n', blen))) {
318 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
319 if(result == -1 && errno == EINTR)
326 if(newline - buffer >= len)
329 len = newline - buffer;
331 memcpy(line, buffer, len);
333 memmove(buffer, newline + 1, blen - len - 1);
339 bool recvdata(int fd, char *data, size_t len) {
341 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
342 if(result == -1 && errno == EINTR)
349 memcpy(data, buffer, len);
350 memmove(buffer, buffer + len, blen - len);
356 bool sendline(int fd, char *format, ...) {
357 static char buffer[4096];
362 va_start(ap, format);
363 blen = vsnprintf(buffer, sizeof buffer, format, ap);
366 if(blen < 0 || blen >= sizeof buffer)
373 int result = send(fd, p, blen, 0);
374 if(result == -1 && errno == EINTR)
376 else if(result <= 0);
385 void pcap(int fd, FILE *out) {
386 sendline(fd, "%d %d", CONTROL, REQ_PCAP);
394 uint32_t tz_accuracy;
414 fwrite(&header, sizeof header, 1, out);
418 while(recvline(fd, line, sizeof line)) {
420 int n = sscanf(line, "%d %d %d", &code, &req, &len);
421 gettimeofday(&tv, NULL);
422 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
424 if(!recvdata(fd, data, len))
426 packet.tv_sec = tv.tv_sec;
427 packet.tv_usec = tv.tv_usec;
429 packet.origlen = len;
430 fwrite(&packet, sizeof packet, 1, out);
431 fwrite(data, len, 1, out);
436 int main(int argc, char *argv[], char *envp[]) {
442 program_name = argv[0];
444 if(!parse_options(argc, argv))
450 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
451 VERSION, __DATE__, __TIME__, PROT_CURRENT);
452 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
453 "See the AUTHORS file for a complete list.\n\n"
454 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
455 "and you are welcome to redistribute it under certain conditions;\n"
456 "see the file COPYING for details.\n");
467 fprintf(stderr, "Not enough arguments.\n");
472 // First handle commands that don't involve connecting to a running tinc daemon.
474 if(!strcasecmp(argv[optind], "generate-keys")) {
475 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
478 if(!strcasecmp(argv[optind], "start")) {
480 execve(SBINDIR "/tincd", argv, envp);
481 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
486 * Now handle commands that do involve connecting to a running tinc daemon.
487 * Authenticate the server by ensuring the parent directory can be
488 * traversed only by root. Note this is not totally race-free unless all
489 * ancestors are writable only by trusted users, which we don't verify.
492 FILE *f = fopen(controlcookiename, "r");
494 fprintf(stderr, "Could not open control socket cookie file %s: %s\n", controlcookiename, strerror(errno));
497 if(fscanf(f, "%1024s %128s %d", controlcookie, port, &pid) != 3) {
498 fprintf(stderr, "Could not parse control socket cookie file %s\n", controlcookiename);
503 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
504 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
509 struct addrinfo hints = {
510 .ai_family = AF_UNSPEC,
511 .ai_socktype = SOCK_STREAM,
512 .ai_protocol = IPPROTO_TCP,
516 struct addrinfo *res = NULL;
518 if(getaddrinfo(host, port, &hints, &res) || !res) {
519 fprintf(stderr, "Cannot resolve %s port %s: %s", host ?: "localhost", port, strerror(errno));
523 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
525 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
530 unsigned long arg = 0;
532 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
533 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
537 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
538 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host ?: "localhost", port, sockstrerror(sockerrno));
546 int code, version, req;
548 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
549 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
550 sockstrerror(sockerrno));
554 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
556 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
557 fprintf(stderr, "Could not fully establish control socket connection\n");
561 if(!strcasecmp(argv[optind], "pid")) {
566 if(!strcasecmp(argv[optind], "stop")) {
567 sendline(fd, "%d %d", CONTROL, REQ_STOP);
568 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
569 fprintf(stderr, "Could not stop tinc daemon\n");
575 if(!strcasecmp(argv[optind], "reload")) {
576 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
577 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
578 fprintf(stderr, "Could not reload tinc daemon\n");
584 if(!strcasecmp(argv[optind], "restart")) {
585 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
586 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
587 fprintf(stderr, "Could not restart tinc daemon\n");
593 if(!strcasecmp(argv[optind], "retry")) {
594 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
595 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
596 fprintf(stderr, "Could not retry outgoing connections\n");
602 if(!strcasecmp(argv[optind], "dump")) {
603 if(argc < optind + 2) {
604 fprintf(stderr, "Not enough arguments.\n");
609 bool do_graph = false;
611 if(!strcasecmp(argv[optind+1], "nodes"))
612 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
613 else if(!strcasecmp(argv[optind+1], "edges"))
614 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
615 else if(!strcasecmp(argv[optind+1], "subnets"))
616 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
617 else if(!strcasecmp(argv[optind+1], "connections"))
618 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
619 else if(!strcasecmp(argv[optind+1], "graph")) {
620 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
621 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
623 printf("digraph {\n");
625 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
630 while(recvline(fd, line, sizeof line)) {
631 char node1[4096], node2[4096];
632 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
634 if(do_graph && req == REQ_DUMP_NODES)
646 printf("%s\n", line + 5);
648 if(req == REQ_DUMP_NODES)
649 printf(" %s [label = \"%s\"];\n", node1, node1);
651 printf(" %s -> %s;\n", node1, node2);
655 fprintf(stderr, "Error receiving dump\n");
659 if(!strcasecmp(argv[optind], "purge")) {
660 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
661 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
662 fprintf(stderr, "Could not purge tinc daemon\n");
668 if(!strcasecmp(argv[optind], "debug")) {
669 int debuglevel, origlevel;
671 if(argc != optind + 2) {
672 fprintf(stderr, "Invalid arguments.\n");
675 debuglevel = atoi(argv[optind+1]);
677 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
678 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
679 fprintf(stderr, "Could not purge tinc daemon\n");
683 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
687 if(!strcasecmp(argv[optind], "connect")) {
688 if(argc != optind + 2) {
689 fprintf(stderr, "Invalid arguments.\n");
692 char *name = argv[optind + 1];
694 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
695 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
696 fprintf(stderr, "Could not connect to %s\n", name);
702 if(!strcasecmp(argv[optind], "disconnect")) {
703 if(argc != optind + 2) {
704 fprintf(stderr, "Invalid arguments.\n");
707 char *name = argv[optind + 1];
709 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
710 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
711 fprintf(stderr, "Could not disconnect %s\n", name);
718 if(!strcasecmp(argv[optind], "top")) {
724 if(!strcasecmp(argv[optind], "pcap")) {
729 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);