2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2012 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 Partially 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 " disconnect NODE Close meta connection with NODE\n"
95 " top Show real-time statistics\n"
97 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
98 " log [level] Dump log output [up to the specified level]\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);
143 netname = getenv("NETNAME");
145 netname = xstrdup(netname);
151 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
157 /* Check stdin and stdout */
158 if(isatty(0) && isatty(1)) {
159 /* Ask for a file and/or directory name. */
160 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
164 if(fgets(buf, sizeof buf, stdin) == NULL) {
165 fprintf(stderr, "Error while reading stdin: %s\n",
170 size_t len = strlen(buf);
179 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
181 if(filename[0] != '/') {
183 /* The directory is a relative path or a filename. */
184 directory = get_current_dir_name();
185 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
189 umask(0077); /* Disallow everything for group and other */
191 /* Open it first to keep the inode busy */
193 r = fopen(filename, mode);
196 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
204 Generate a public/private ECDSA keypair, and ask for a file to store
207 static bool ecdsa_keygen() {
212 fprintf(stderr, "Generating ECDSA keypair:\n");
214 if(!ecdsa_generate(&key)) {
215 fprintf(stderr, "Error during key generation!\n");
218 fprintf(stderr, "Done.\n");
220 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
221 f = ask_and_open(filename, "private ECDSA key", "a");
227 /* Make it unreadable for others. */
228 fchmod(fileno(f), 0600);
232 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
234 ecdsa_write_pem_private_key(&key, f);
240 xasprintf(&filename, "%s/hosts/%s", confbase, name);
242 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
244 f = ask_and_open(filename, "public ECDSA key", "a");
250 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
252 char *pubkey = ecdsa_get_base64_public_key(&key);
253 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
263 Generate a public/private RSA keypair, and ask for a file to store
266 static bool rsa_keygen(int bits) {
271 fprintf(stderr, "Generating %d bits keys:\n", bits);
273 if(!rsa_generate(&key, bits, 0x10001)) {
274 fprintf(stderr, "Error during key generation!\n");
277 fprintf(stderr, "Done.\n");
279 xasprintf(&filename, "%s/rsa_key.priv", confbase);
280 f = ask_and_open(filename, "private RSA key", "a");
286 /* Make it unreadable for others. */
287 fchmod(fileno(f), 0600);
291 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
293 rsa_write_pem_private_key(&key, f);
299 xasprintf(&filename, "%s/hosts/%s", confbase, name);
301 xasprintf(&filename, "%s/rsa_key.pub", confbase);
303 f = ask_and_open(filename, "public RSA key", "a");
309 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
311 rsa_write_pem_public_key(&key, f);
320 Set all files and paths according to netname
322 static void make_names(void) {
325 char installdir[1024] = "";
326 long len = sizeof installdir;
330 xasprintf(&identname, "tinc.%s", netname);
332 identname = xstrdup("tinc");
335 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
336 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
339 xasprintf(&confbase, "%s/%s", installdir, netname);
341 xasprintf(&confbase, "%s", installdir);
345 xasprintf(&pidfilename, "%s/pid", confbase);
353 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
357 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
359 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
362 xasprintf(&confbase, CONFDIR "/tinc");
366 static char buffer[4096];
367 static size_t blen = 0;
369 bool recvline(int fd, char *line, size_t len) {
370 char *newline = NULL;
372 while(!(newline = memchr(buffer, '\n', blen))) {
373 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
374 if(result == -1 && errno == EINTR)
381 if(newline - buffer >= len)
384 len = newline - buffer;
386 memcpy(line, buffer, len);
388 memmove(buffer, newline + 1, blen - len - 1);
394 static bool recvdata(int fd, char *data, size_t len) {
396 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
397 if(result == -1 && errno == EINTR)
404 memcpy(data, buffer, len);
405 memmove(buffer, buffer + len, blen - len);
411 bool sendline(int fd, char *format, ...) {
412 static char buffer[4096];
417 va_start(ap, format);
418 blen = vsnprintf(buffer, sizeof buffer, format, ap);
421 if(blen < 1 || blen >= sizeof buffer)
428 int result = send(fd, p, blen, 0);
429 if(result == -1 && errno == EINTR)
440 static void pcap(int fd, FILE *out, int snaplen) {
441 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
449 uint32_t tz_accuracy;
456 snaplen ?: sizeof data,
469 fwrite(&header, sizeof header, 1, out);
473 while(recvline(fd, line, sizeof line)) {
475 int n = sscanf(line, "%d %d %d", &code, &req, &len);
476 gettimeofday(&tv, NULL);
477 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
479 if(!recvdata(fd, data, len))
481 packet.tv_sec = tv.tv_sec;
482 packet.tv_usec = tv.tv_usec;
484 packet.origlen = len;
485 fwrite(&packet, sizeof packet, 1, out);
486 fwrite(data, len, 1, out);
491 static void logcontrol(int fd, FILE *out, int level) {
492 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
496 while(recvline(fd, line, sizeof line)) {
498 int n = sscanf(line, "%d %d %d", &code, &req, &len);
499 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
501 if(!recvdata(fd, data, len))
503 fwrite(data, len, 1, out);
510 static bool remove_service(void) {
511 SC_HANDLE manager = NULL;
512 SC_HANDLE service = NULL;
513 SERVICE_STATUS status = {0};
515 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
517 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
521 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
524 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
528 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
529 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
531 fprintf(stderr, "%s service stopped\n", identname);
533 if(!DeleteService(service)) {
534 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
538 fprintf(stderr, "%s service removed\n", identname);
544 int main(int argc, char *argv[]) {
551 program_name = argv[0];
553 if(!parse_options(argc, argv))
559 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
560 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
561 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
562 "See the AUTHORS file for a complete list.\n\n"
563 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
564 "and you are welcome to redistribute it under certain conditions;\n"
565 "see the file COPYING for details.\n");
576 fprintf(stderr, "Not enough arguments.\n");
581 // First handle commands that don't involve connecting to a running tinc daemon.
583 if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
584 return !rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048);
587 if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
588 return !ecdsa_keygen();
591 if(!strcasecmp(argv[optind], "generate-keys")) {
592 return !(rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
595 if(!strcasecmp(argv[optind], "start")) {
598 char *slash = strrchr(argv[0], '/');
600 if ((c = strrchr(argv[0], '\\')) > slash)
604 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
605 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
610 for(i = j = 1; argv[i]; ++i)
611 if (i != optind && strcmp(argv[i], "--") != 0)
615 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
620 * Now handle commands that do involve connecting to a running tinc daemon.
621 * Authenticate the server by ensuring the parent directory can be
622 * traversed only by root. Note this is not totally race-free unless all
623 * ancestors are writable only by trusted users, which we don't verify.
626 FILE *f = fopen(pidfilename, "r");
628 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
631 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
632 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
637 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
638 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
643 struct addrinfo hints = {
644 .ai_family = AF_UNSPEC,
645 .ai_socktype = SOCK_STREAM,
646 .ai_protocol = IPPROTO_TCP,
650 struct addrinfo *res = NULL;
652 if(getaddrinfo(host, port, &hints, &res) || !res) {
653 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
657 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
659 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
664 unsigned long arg = 0;
666 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
667 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
671 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
672 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
680 int code, version, req;
682 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
683 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
684 sockstrerror(sockerrno));
688 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
690 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
691 fprintf(stderr, "Could not fully establish control socket connection\n");
695 if(!strcasecmp(argv[optind], "pid")) {
700 if(!strcasecmp(argv[optind], "stop")) {
702 sendline(fd, "%d %d", CONTROL, REQ_STOP);
703 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
704 fprintf(stderr, "Could not stop tinc daemon\n");
708 if(!remove_service())
714 if(!strcasecmp(argv[optind], "reload")) {
715 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
716 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
717 fprintf(stderr, "Could not reload tinc daemon\n");
723 if(!strcasecmp(argv[optind], "restart")) {
724 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
725 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
726 fprintf(stderr, "Could not restart tinc daemon\n");
732 if(!strcasecmp(argv[optind], "retry")) {
733 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
734 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
735 fprintf(stderr, "Could not retry outgoing connections\n");
741 if(!strcasecmp(argv[optind], "dump")) {
742 if(argc < optind + 2) {
743 fprintf(stderr, "Not enough arguments.\n");
748 bool do_graph = false;
750 if(!strcasecmp(argv[optind+1], "nodes"))
751 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
752 else if(!strcasecmp(argv[optind+1], "edges"))
753 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
754 else if(!strcasecmp(argv[optind+1], "subnets"))
755 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
756 else if(!strcasecmp(argv[optind+1], "connections"))
757 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
758 else if(!strcasecmp(argv[optind+1], "graph")) {
759 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
760 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
762 printf("digraph {\n");
764 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
769 while(recvline(fd, line, sizeof line)) {
770 char node1[4096], node2[4096];
771 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
773 if(do_graph && req == REQ_DUMP_NODES)
785 printf("%s\n", line + 5);
787 if(req == REQ_DUMP_NODES)
788 printf(" %s [label = \"%s\"];\n", node1, node1);
790 printf(" %s -> %s;\n", node1, node2);
794 fprintf(stderr, "Error receiving dump\n");
798 if(!strcasecmp(argv[optind], "purge")) {
799 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
800 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
801 fprintf(stderr, "Could not purge tinc daemon\n");
807 if(!strcasecmp(argv[optind], "debug")) {
808 int debuglevel, origlevel;
810 if(argc != optind + 2) {
811 fprintf(stderr, "Invalid arguments.\n");
814 debuglevel = atoi(argv[optind+1]);
816 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
817 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
818 fprintf(stderr, "Could not purge tinc daemon\n");
822 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
826 if(!strcasecmp(argv[optind], "connect")) {
827 if(argc != optind + 2) {
828 fprintf(stderr, "Invalid arguments.\n");
831 char *name = argv[optind + 1];
833 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
834 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
835 fprintf(stderr, "Could not connect to %s\n", name);
841 if(!strcasecmp(argv[optind], "disconnect")) {
842 if(argc != optind + 2) {
843 fprintf(stderr, "Invalid arguments.\n");
846 char *name = argv[optind + 1];
848 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
849 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
850 fprintf(stderr, "Could not disconnect %s\n", name);
857 if(!strcasecmp(argv[optind], "top")) {
863 if(!strcasecmp(argv[optind], "pcap")) {
864 pcap(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : 0);
868 if(!strcasecmp(argv[optind], "log")) {
869 logcontrol(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : -1);
873 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);