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 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 Dump traffic in pcap format\n"
99 printf("Report bugs to tinc@tinc-vpn.org.\n");
103 static bool parse_options(int argc, char **argv) {
105 int option_index = 0;
107 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
109 case 0: /* long option */
112 case 'c': /* config file */
113 confbase = xstrdup(optarg);
116 case 'n': /* net name given */
117 netname = xstrdup(optarg);
120 case 1: /* show help */
124 case 2: /* show version */
128 case 5: /* open control socket here */
129 pidfilename = xstrdup(optarg);
142 netname = getenv("NETNAME");
144 netname = xstrdup(netname);
150 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
156 /* Check stdin and stdout */
157 if(isatty(0) && isatty(1)) {
158 /* Ask for a file and/or directory name. */
159 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
163 if(fgets(buf, sizeof buf, stdin) == NULL) {
164 fprintf(stderr, "Error while reading stdin: %s\n",
169 size_t len = strlen(buf);
178 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
180 if(filename[0] != '/') {
182 /* The directory is a relative path or a filename. */
183 directory = get_current_dir_name();
184 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
188 umask(0077); /* Disallow everything for group and other */
190 /* Open it first to keep the inode busy */
192 r = fopen(filename, mode);
195 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
203 Generate a public/private ECDSA keypair, and ask for a file to store
206 static bool ecdsa_keygen() {
211 fprintf(stderr, "Generating ECDSA keypair:\n");
213 if(!ecdsa_generate(&key)) {
214 fprintf(stderr, "Error during key generation!\n");
217 fprintf(stderr, "Done.\n");
219 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
220 f = ask_and_open(filename, "private ECDSA key", "a");
226 /* Make it unreadable for others. */
227 fchmod(fileno(f), 0600);
231 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
233 ecdsa_write_pem_private_key(&key, f);
239 xasprintf(&filename, "%s/hosts/%s", confbase, name);
241 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
243 f = ask_and_open(filename, "public ECDSA key", "a");
249 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
251 char *pubkey = ecdsa_get_base64_public_key(&key);
252 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
262 Generate a public/private RSA keypair, and ask for a file to store
265 static bool rsa_keygen(int bits) {
270 fprintf(stderr, "Generating %d bits keys:\n", bits);
272 if(!rsa_generate(&key, bits, 0x10001)) {
273 fprintf(stderr, "Error during key generation!\n");
276 fprintf(stderr, "Done.\n");
278 xasprintf(&filename, "%s/rsa_key.priv", confbase);
279 f = ask_and_open(filename, "private RSA key", "a");
285 /* Make it unreadable for others. */
286 fchmod(fileno(f), 0600);
290 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
292 rsa_write_pem_private_key(&key, f);
298 xasprintf(&filename, "%s/hosts/%s", confbase, name);
300 xasprintf(&filename, "%s/rsa_key.pub", confbase);
302 f = ask_and_open(filename, "public RSA key", "a");
308 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
310 rsa_write_pem_public_key(&key, f);
319 Set all files and paths according to netname
321 static void make_names(void) {
324 char installdir[1024] = "";
325 long len = sizeof installdir;
329 xasprintf(&identname, "tinc.%s", netname);
331 identname = xstrdup("tinc");
334 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
335 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
338 xasprintf(&confbase, "%s/%s", installdir, netname);
340 xasprintf(&confbase, "%s", installdir);
344 xasprintf(&pidfilename, "%s/pid", confbase);
352 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
356 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
358 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
361 xasprintf(&confbase, CONFDIR "/tinc");
365 static char buffer[4096];
366 static size_t blen = 0;
368 bool recvline(int fd, char *line, size_t len) {
369 char *newline = NULL;
371 while(!(newline = memchr(buffer, '\n', blen))) {
372 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
373 if(result == -1 && errno == EINTR)
380 if(newline - buffer >= len)
383 len = newline - buffer;
385 memcpy(line, buffer, len);
387 memmove(buffer, newline + 1, blen - len - 1);
393 bool recvdata(int fd, char *data, size_t len) {
395 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
396 if(result == -1 && errno == EINTR)
403 memcpy(data, buffer, len);
404 memmove(buffer, buffer + len, blen - len);
410 bool sendline(int fd, char *format, ...) {
411 static char buffer[4096];
416 va_start(ap, format);
417 blen = vsnprintf(buffer, sizeof buffer, format, ap);
420 if(blen < 1 || blen >= sizeof buffer)
427 int result = send(fd, p, blen, 0);
428 if(result == -1 && errno == EINTR)
439 void pcap(int fd, FILE *out) {
440 sendline(fd, "%d %d", CONTROL, REQ_PCAP);
448 uint32_t tz_accuracy;
468 fwrite(&header, sizeof header, 1, out);
472 while(recvline(fd, line, sizeof line)) {
474 int n = sscanf(line, "%d %d %d", &code, &req, &len);
475 gettimeofday(&tv, NULL);
476 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
478 if(!recvdata(fd, data, len))
480 packet.tv_sec = tv.tv_sec;
481 packet.tv_usec = tv.tv_usec;
483 packet.origlen = len;
484 fwrite(&packet, sizeof packet, 1, out);
485 fwrite(data, len, 1, out);
491 static bool remove_service(void) {
492 SC_HANDLE manager = NULL;
493 SC_HANDLE service = NULL;
494 SERVICE_STATUS status = {0};
496 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
498 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
502 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
505 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
509 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
510 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
512 fprintf(stderr, "%s service stopped\n", identname);
514 if(!DeleteService(service)) {
515 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
519 fprintf(stderr, "%s service removed\n", identname);
525 int main(int argc, char *argv[]) {
532 program_name = argv[0];
534 if(!parse_options(argc, argv))
540 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
541 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
542 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
543 "See the AUTHORS file for a complete list.\n\n"
544 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
545 "and you are welcome to redistribute it under certain conditions;\n"
546 "see the file COPYING for details.\n");
557 fprintf(stderr, "Not enough arguments.\n");
562 // First handle commands that don't involve connecting to a running tinc daemon.
564 if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
565 return !rsa_keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
568 if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
569 return !ecdsa_keygen();
572 if(!strcasecmp(argv[optind], "generate-keys")) {
573 return !(rsa_keygen(optind > argc ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
576 if(!strcasecmp(argv[optind], "start")) {
579 char *slash = strrchr(argv[0], '/');
581 if ((c = strrchr(argv[0], '\\')) > slash)
585 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
586 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
591 for(i = j = 1; argv[i]; ++i)
592 if (i != optind && strcmp(argv[i], "--") != 0)
596 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
601 * Now handle commands that do involve connecting to a running tinc daemon.
602 * Authenticate the server by ensuring the parent directory can be
603 * traversed only by root. Note this is not totally race-free unless all
604 * ancestors are writable only by trusted users, which we don't verify.
607 FILE *f = fopen(pidfilename, "r");
609 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
612 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
613 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
618 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
619 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
624 struct addrinfo hints = {
625 .ai_family = AF_UNSPEC,
626 .ai_socktype = SOCK_STREAM,
627 .ai_protocol = IPPROTO_TCP,
631 struct addrinfo *res = NULL;
633 if(getaddrinfo(host, port, &hints, &res) || !res) {
634 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
638 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
640 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
645 unsigned long arg = 0;
647 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
648 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
652 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
653 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
661 int code, version, req;
663 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
664 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
665 sockstrerror(sockerrno));
669 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
671 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
672 fprintf(stderr, "Could not fully establish control socket connection\n");
676 if(!strcasecmp(argv[optind], "pid")) {
681 if(!strcasecmp(argv[optind], "stop")) {
683 sendline(fd, "%d %d", CONTROL, REQ_STOP);
684 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
685 fprintf(stderr, "Could not stop tinc daemon\n");
689 if(!remove_service())
695 if(!strcasecmp(argv[optind], "reload")) {
696 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
697 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
698 fprintf(stderr, "Could not reload tinc daemon\n");
704 if(!strcasecmp(argv[optind], "restart")) {
705 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
706 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
707 fprintf(stderr, "Could not restart tinc daemon\n");
713 if(!strcasecmp(argv[optind], "retry")) {
714 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
715 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
716 fprintf(stderr, "Could not retry outgoing connections\n");
722 if(!strcasecmp(argv[optind], "dump")) {
723 if(argc < optind + 2) {
724 fprintf(stderr, "Not enough arguments.\n");
729 bool do_graph = false;
731 if(!strcasecmp(argv[optind+1], "nodes"))
732 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
733 else if(!strcasecmp(argv[optind+1], "edges"))
734 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
735 else if(!strcasecmp(argv[optind+1], "subnets"))
736 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
737 else if(!strcasecmp(argv[optind+1], "connections"))
738 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
739 else if(!strcasecmp(argv[optind+1], "graph")) {
740 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
741 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
743 printf("digraph {\n");
745 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
750 while(recvline(fd, line, sizeof line)) {
751 char node1[4096], node2[4096];
752 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
754 if(do_graph && req == REQ_DUMP_NODES)
766 printf("%s\n", line + 5);
768 if(req == REQ_DUMP_NODES)
769 printf(" %s [label = \"%s\"];\n", node1, node1);
771 printf(" %s -> %s;\n", node1, node2);
775 fprintf(stderr, "Error receiving dump\n");
779 if(!strcasecmp(argv[optind], "purge")) {
780 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
781 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
782 fprintf(stderr, "Could not purge tinc daemon\n");
788 if(!strcasecmp(argv[optind], "debug")) {
789 int debuglevel, origlevel;
791 if(argc != optind + 2) {
792 fprintf(stderr, "Invalid arguments.\n");
795 debuglevel = atoi(argv[optind+1]);
797 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
798 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
799 fprintf(stderr, "Could not purge tinc daemon\n");
803 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
807 if(!strcasecmp(argv[optind], "connect")) {
808 if(argc != optind + 2) {
809 fprintf(stderr, "Invalid arguments.\n");
812 char *name = argv[optind + 1];
814 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
815 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
816 fprintf(stderr, "Could not connect to %s\n", name);
822 if(!strcasecmp(argv[optind], "disconnect")) {
823 if(argc != optind + 2) {
824 fprintf(stderr, "Invalid arguments.\n");
827 char *name = argv[optind + 1];
829 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
830 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
831 fprintf(stderr, "Could not disconnect %s\n", name);
838 if(!strcasecmp(argv[optind], "top")) {
844 if(!strcasecmp(argv[optind], "pcap")) {
849 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);