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 char *program_name = NULL;
35 /* If nonzero, display usage information and exit. */
36 bool show_help = false;
38 /* If nonzero, print the version on standard output and exit. */
39 bool show_version = false;
41 /* If nonzero, it will attempt to kill a running tincd and exit. */
44 /* If nonzero, generate public/private keypair for this host/net. */
45 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;
55 static struct WSAData wsa_state;
58 static struct option const long_options[] = {
59 {"config", required_argument, NULL, 'c'},
60 {"net", required_argument, NULL, 'n'},
61 {"help", no_argument, NULL, 1},
62 {"version", no_argument, NULL, 2},
63 {"controlcookie", required_argument, NULL, 5},
67 static void usage(bool status) {
69 fprintf(stderr, "Try `%s --help\' for more information.\n",
72 printf("Usage: %s [options] command\n\n", program_name);
73 printf("Valid options are:\n"
74 " -c, --config=DIR Read configuration options from DIR.\n"
75 " -n, --net=NETNAME Connect to net NETNAME.\n"
76 " --controlcookie=FILENAME Read control socket from FILENAME.\n"
77 " --help Display this help and exit.\n"
78 " --version Output version information and exit.\n"
80 "Valid commands are:\n"
81 " start Start tincd.\n"
83 " restart Restart tincd.\n"
84 " reload Reload configuration of running tincd.\n"
85 " pid Show PID of currently running tincd.\n"
86 " generate-keys [bits] Generate a new public/private keypair.\n"
87 " dump Dump a list of one of the following things:\n"
88 " nodes - all known nodes in the VPN\n"
89 " edges - all known connections in the VPN\n"
90 " subnets - all known subnets in the VPN\n"
91 " connections - all meta connections with ourself\n"
92 " graph - graph of the VPN in dotty format\n"
93 " purge Purge unreachable nodes\n"
94 " debug N Set debug level\n"
95 " retry Retry all outgoing connections\n"
96 " reload Partial reload of configuration\n"
97 " disconnect NODE Close meta connection with NODE\n"
99 " top Show real-time statistics\n"
102 printf("Report bugs to tinc@tinc-vpn.org.\n");
106 static bool parse_options(int argc, char **argv) {
108 int option_index = 0;
110 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
112 case 0: /* long option */
115 case 'c': /* config file */
116 confbase = xstrdup(optarg);
119 case 'n': /* net name given */
120 netname = xstrdup(optarg);
123 case 1: /* show help */
127 case 2: /* show version */
131 case 5: /* open control socket here */
132 controlcookiename = xstrdup(optarg);
147 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
154 /* Check stdin and stdout */
155 if(isatty(0) && isatty(1)) {
156 /* Ask for a file and/or directory name. */
157 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
161 if(fgets(buf, sizeof buf, stdin) < 0) {
162 fprintf(stderr, "Error while reading stdin: %s\n",
176 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
178 if(filename[0] != '/') {
180 /* The directory is a relative path or a filename. */
181 directory = get_current_dir_name();
182 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
186 umask(0077); /* Disallow everything for group and other */
188 /* Open it first to keep the inode busy */
190 r = fopen(filename, mode);
193 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
201 Generate a public/private RSA keypair, and ask for a file to store
204 static bool keygen(int bits) {
209 fprintf(stderr, "Generating %d bits keys:\n", bits);
211 if(!rsa_generate(&key, bits, 0x10001)) {
212 fprintf(stderr, "Error during key generation!\n");
215 fprintf(stderr, "Done.\n");
217 xasprintf(&filename, "%s/rsa_key.priv", confbase);
218 f = ask_and_open(filename, "private RSA key", "a");
224 /* Make it unreadable for others. */
225 fchmod(fileno(f), 0600);
229 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
231 rsa_write_pem_private_key(&key, f);
237 xasprintf(&filename, "%s/hosts/%s", confbase, name);
239 xasprintf(&filename, "%s/rsa_key.pub", confbase);
241 f = ask_and_open(filename, "public RSA key", "a");
247 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
249 rsa_write_pem_public_key(&key, f);
258 Set all files and paths according to netname
260 static void make_names(void) {
263 char installdir[1024] = "";
264 long len = sizeof installdir;
268 xasprintf(&identname, "tinc.%s", netname);
270 identname = xstrdup("tinc");
273 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
274 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
277 xasprintf(&confbase, "%s/%s", installdir, netname);
279 xasprintf(&confbase, "%s", installdir);
282 if(!controlcookiename)
283 xasprintf(&controlcookiename, "%s/cookie", confbase);
290 if(!controlcookiename)
291 xasprintf(&controlcookiename, "%s/run/%s.cookie", LOCALSTATEDIR, identname);
295 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
297 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
300 xasprintf(&confbase, CONFDIR "/tinc");
304 bool recvline(int fd, char *line, size_t len) {
305 static char buffer[4096];
306 static size_t blen = 0;
307 char *newline = NULL;
309 while(!(newline = memchr(buffer, '\n', blen))) {
310 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
311 if(result == -1 && errno == EINTR)
318 if(newline - buffer >= len)
321 len = newline - buffer;
323 memcpy(line, buffer, len);
325 memmove(buffer, newline + 1, blen - len - 1);
331 bool sendline(int fd, char *format, ...) {
332 static char buffer[4096];
337 va_start(ap, format);
338 blen = vsnprintf(buffer, sizeof buffer, format, ap);
341 if(blen < 0 || blen >= sizeof buffer)
348 int result = send(fd, p, blen, 0);
349 if(result == -1 && errno == EINTR)
351 else if(result <= 0);
360 int main(int argc, char *argv[], char *envp[]) {
366 program_name = argv[0];
368 if(!parse_options(argc, argv))
374 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
375 VERSION, __DATE__, __TIME__, PROT_CURRENT);
376 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
377 "See the AUTHORS file for a complete list.\n\n"
378 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
379 "and you are welcome to redistribute it under certain conditions;\n"
380 "see the file COPYING for details.\n");
391 fprintf(stderr, "Not enough arguments.\n");
396 // First handle commands that don't involve connecting to a running tinc daemon.
398 if(!strcasecmp(argv[optind], "generate-keys")) {
399 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
402 if(!strcasecmp(argv[optind], "start")) {
404 execve(SBINDIR "/tincd", argv, envp);
405 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
410 * Now handle commands that do involve connecting to a running tinc daemon.
411 * Authenticate the server by ensuring the parent directory can be
412 * traversed only by root. Note this is not totally race-free unless all
413 * ancestors are writable only by trusted users, which we don't verify.
416 FILE *f = fopen(controlcookiename, "r");
418 fprintf(stderr, "Could not open control socket cookie file %s: %s\n", controlcookiename, strerror(errno));
421 if(fscanf(f, "%1024s %d %d", controlcookie, &port, &pid) != 3) {
422 fprintf(stderr, "Could not parse control socket cookie file %s\n", controlcookiename);
427 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
428 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
433 struct sockaddr_in addr;
434 memset(&addr, 0, sizeof addr);
435 addr.sin_family = AF_INET;
436 addr.sin_addr.s_addr = htonl(0x7f000001);
437 addr.sin_port = htons(port);
439 fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
441 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
446 unsigned long arg = 0;
448 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
449 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
453 if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
455 fprintf(stderr, "Cannot connect to %s: %s\n", controlcookiename, sockstrerror(sockerrno));
461 int code, version, req;
463 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
464 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
465 sockstrerror(sockerrno));
469 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
471 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
472 fprintf(stderr, "Could not fully establish control socket connection\n");
476 if(!strcasecmp(argv[optind], "pid")) {
481 if(!strcasecmp(argv[optind], "stop")) {
482 sendline(fd, "%d %d", CONTROL, REQ_STOP);
483 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
484 fprintf(stderr, "Could not stop tinc daemon\n");
490 if(!strcasecmp(argv[optind], "reload")) {
491 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
492 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
493 fprintf(stderr, "Could not reload tinc daemon\n");
499 if(!strcasecmp(argv[optind], "restart")) {
500 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
501 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
502 fprintf(stderr, "Could not restart tinc daemon\n");
508 if(!strcasecmp(argv[optind], "retry")) {
509 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
510 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
511 fprintf(stderr, "Could not retry outgoing connections\n");
517 if(!strcasecmp(argv[optind], "dump")) {
518 if(argc < optind + 2) {
519 fprintf(stderr, "Not enough arguments.\n");
524 bool do_graph = false;
526 if(!strcasecmp(argv[optind+1], "nodes"))
527 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
528 else if(!strcasecmp(argv[optind+1], "edges"))
529 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
530 else if(!strcasecmp(argv[optind+1], "subnets"))
531 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
532 else if(!strcasecmp(argv[optind+1], "connections"))
533 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
534 else if(!strcasecmp(argv[optind+1], "graph")) {
535 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
536 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
538 printf("digraph {\n");
540 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
545 while(recvline(fd, line, sizeof line)) {
546 char node1[4096], node2[4096];
547 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
549 if(do_graph && req == REQ_DUMP_NODES)
561 printf("%s\n", line + 5);
563 if(req == REQ_DUMP_NODES)
564 printf(" %s [label = \"%s\"];\n", node1, node1);
566 printf(" %s -> %s;\n", node1, node2);
570 fprintf(stderr, "Error receiving dump\n");
574 if(!strcasecmp(argv[optind], "purge")) {
575 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
576 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
577 fprintf(stderr, "Could not purge tinc daemon\n");
583 if(!strcasecmp(argv[optind], "debug")) {
584 int debuglevel, origlevel;
586 if(argc != optind + 2) {
587 fprintf(stderr, "Invalid arguments.\n");
590 debuglevel = atoi(argv[optind+1]);
592 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
593 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
594 fprintf(stderr, "Could not purge tinc daemon\n");
598 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
602 if(!strcasecmp(argv[optind], "connect")) {
603 if(argc != optind + 2) {
604 fprintf(stderr, "Invalid arguments.\n");
607 char *name = argv[optind + 1];
609 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
610 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
611 fprintf(stderr, "Could not connect to %s\n", name);
617 if(!strcasecmp(argv[optind], "disconnect")) {
618 if(argc != optind + 2) {
619 fprintf(stderr, "Invalid arguments.\n");
622 char *name = argv[optind + 1];
624 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
625 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
626 fprintf(stderr, "Could not disconnect %s\n", name);
633 if(!strcasecmp(argv[optind], "top")) {
639 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);