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 " init [name] Create initial configuration files.\n"
77 " start Start tincd.\n"
79 " restart Restart tincd.\n"
80 " reload Partially reload configuration of running tincd.\n"
81 " pid Show PID of currently running tincd.\n"
82 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
83 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
84 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
85 " dump Dump a list of one of the following things:\n"
86 " nodes - all known nodes in the VPN\n"
87 " edges - all known connections in the VPN\n"
88 " subnets - all known subnets in the VPN\n"
89 " connections - all meta connections with ourself\n"
90 " graph - graph of the VPN in dotty format\n"
91 " purge Purge unreachable nodes\n"
92 " debug N Set debug level\n"
93 " retry Retry all outgoing connections\n"
94 " disconnect NODE Close meta connection with NODE\n"
96 " top Show real-time statistics\n"
98 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
99 " log [level] Dump log output [up to the specified level]\n"
101 printf("Report bugs to tinc@tinc-vpn.org.\n");
105 static bool parse_options(int argc, char **argv) {
107 int option_index = 0;
109 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
111 case 0: /* long option */
114 case 'c': /* config file */
115 confbase = xstrdup(optarg);
118 case 'n': /* net name given */
119 netname = xstrdup(optarg);
122 case 1: /* show help */
126 case 2: /* show version */
130 case 5: /* open control socket here */
131 pidfilename = xstrdup(optarg);
144 netname = getenv("NETNAME");
146 netname = xstrdup(netname);
152 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
158 /* Check stdin and stdout */
159 if(isatty(0) && isatty(1)) {
160 /* Ask for a file and/or directory name. */
161 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
165 if(fgets(buf, sizeof buf, stdin) == NULL) {
166 fprintf(stderr, "Error while reading stdin: %s\n",
171 size_t len = strlen(buf);
180 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
182 if(filename[0] != '/') {
184 /* The directory is a relative path or a filename. */
185 directory = get_current_dir_name();
186 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
190 umask(0077); /* Disallow everything for group and other */
192 /* Open it first to keep the inode busy */
194 r = fopen(filename, mode);
197 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
205 Generate a public/private ECDSA keypair, and ask for a file to store
208 static bool ecdsa_keygen() {
213 fprintf(stderr, "Generating ECDSA keypair:\n");
215 if(!ecdsa_generate(&key)) {
216 fprintf(stderr, "Error during key generation!\n");
219 fprintf(stderr, "Done.\n");
221 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
222 f = ask_and_open(filename, "private ECDSA key", "a");
228 /* Make it unreadable for others. */
229 fchmod(fileno(f), 0600);
233 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
235 ecdsa_write_pem_private_key(&key, f);
241 xasprintf(&filename, "%s/hosts/%s", confbase, name);
243 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
245 f = ask_and_open(filename, "public ECDSA key", "a");
251 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
253 char *pubkey = ecdsa_get_base64_public_key(&key);
254 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
264 Generate a public/private RSA keypair, and ask for a file to store
267 static bool rsa_keygen(int bits) {
272 fprintf(stderr, "Generating %d bits keys:\n", bits);
274 if(!rsa_generate(&key, bits, 0x10001)) {
275 fprintf(stderr, "Error during key generation!\n");
278 fprintf(stderr, "Done.\n");
280 xasprintf(&filename, "%s/rsa_key.priv", confbase);
281 f = ask_and_open(filename, "private RSA key", "a");
287 /* Make it unreadable for others. */
288 fchmod(fileno(f), 0600);
292 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
294 rsa_write_pem_private_key(&key, f);
300 xasprintf(&filename, "%s/hosts/%s", confbase, name);
302 xasprintf(&filename, "%s/rsa_key.pub", confbase);
304 f = ask_and_open(filename, "public RSA key", "a");
310 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
312 rsa_write_pem_public_key(&key, f);
321 Set all files and paths according to netname
323 static void make_names(void) {
326 char installdir[1024] = "";
327 long len = sizeof installdir;
331 xasprintf(&identname, "tinc.%s", netname);
333 identname = xstrdup("tinc");
336 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
337 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
340 xasprintf(&confbase, "%s/%s", installdir, netname);
342 xasprintf(&confbase, "%s", installdir);
346 xasprintf(&pidfilename, "%s/pid", confbase);
354 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
358 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
360 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
363 xasprintf(&confbase, CONFDIR "/tinc");
367 static char buffer[4096];
368 static size_t blen = 0;
370 bool recvline(int fd, char *line, size_t len) {
371 char *newline = NULL;
373 while(!(newline = memchr(buffer, '\n', blen))) {
374 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
375 if(result == -1 && errno == EINTR)
382 if(newline - buffer >= len)
385 len = newline - buffer;
387 memcpy(line, buffer, len);
389 memmove(buffer, newline + 1, blen - len - 1);
395 static bool recvdata(int fd, char *data, size_t len) {
397 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
398 if(result == -1 && errno == EINTR)
405 memcpy(data, buffer, len);
406 memmove(buffer, buffer + len, blen - len);
412 bool sendline(int fd, char *format, ...) {
413 static char buffer[4096];
418 va_start(ap, format);
419 blen = vsnprintf(buffer, sizeof buffer, format, ap);
422 if(blen < 1 || blen >= sizeof buffer)
429 int result = send(fd, p, blen, 0);
430 if(result == -1 && errno == EINTR)
441 static void pcap(int fd, FILE *out, int snaplen) {
442 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
450 uint32_t tz_accuracy;
457 snaplen ?: sizeof data,
470 fwrite(&header, sizeof header, 1, out);
474 while(recvline(fd, line, sizeof line)) {
476 int n = sscanf(line, "%d %d %d", &code, &req, &len);
477 gettimeofday(&tv, NULL);
478 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
480 if(!recvdata(fd, data, len))
482 packet.tv_sec = tv.tv_sec;
483 packet.tv_usec = tv.tv_usec;
485 packet.origlen = len;
486 fwrite(&packet, sizeof packet, 1, out);
487 fwrite(data, len, 1, out);
492 static void logcontrol(int fd, FILE *out, int level) {
493 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
497 while(recvline(fd, line, sizeof line)) {
499 int n = sscanf(line, "%d %d %d", &code, &req, &len);
500 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
502 if(!recvdata(fd, data, len))
504 fwrite(data, len, 1, out);
511 static bool remove_service(void) {
512 SC_HANDLE manager = NULL;
513 SC_HANDLE service = NULL;
514 SERVICE_STATUS status = {0};
516 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
518 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
522 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
525 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
529 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
530 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
532 fprintf(stderr, "%s service stopped\n", identname);
534 if(!DeleteService(service)) {
535 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
539 fprintf(stderr, "%s service removed\n", identname);
545 int main(int argc, char *argv[]) {
552 program_name = argv[0];
554 if(!parse_options(argc, argv))
560 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
561 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
562 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
563 "See the AUTHORS file for a complete list.\n\n"
564 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
565 "and you are welcome to redistribute it under certain conditions;\n"
566 "see the file COPYING for details.\n");
577 fprintf(stderr, "Not enough arguments.\n");
582 // First handle commands that don't involve connecting to a running tinc daemon.
584 if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
585 return !rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048);
588 if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
589 return !ecdsa_keygen();
592 if(!strcasecmp(argv[optind], "generate-keys")) {
593 return !(rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
596 if(!strcasecmp(argv[optind], "start")) {
599 char *slash = strrchr(argv[0], '/');
601 if ((c = strrchr(argv[0], '\\')) > slash)
605 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
606 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
611 for(i = j = 1; argv[i]; ++i)
612 if (i != optind && strcmp(argv[i], "--") != 0)
616 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
620 if(!strcasecmp(argv[optind], "init")) {
621 char *filename = NULL;
622 xasprintf(&filename, "%s/tinc.conf", confbase);
623 if(!access(confbase, F_OK)) {
624 fprintf(stderr, "Configuration file %s already exists!\n", filename);
628 if(optind >= argc - 1) {
629 if(isatty(0) && isatty(1)) {
631 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
633 if(!fgets(buf, sizeof buf, stdin)) {
634 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
637 int len = strlen(buf);
641 fprintf(stderr, "No name given!\n");
646 fprintf(stderr, "No Name given!\n");
650 name = strdup(argv[optind + 1]);
652 fprintf(stderr, "No Name given!\n");
657 for(int i = 0; i < strlen(name); i++) {
658 if(!isalnum(name[i]) && name[i] != '_') {
659 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
664 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
665 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
669 if(mkdir(confbase, 0755) && errno != EEXIST) {
670 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
674 char *filename2 = NULL;
675 xasprintf(&filename2, "%s/hosts", confbase);
676 if(mkdir(filename2, 0755) && errno != EEXIST) {
677 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
681 FILE *f = fopen(filename, "w");
683 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
687 fprintf(f, "Name = %s\n", name);
691 if(!rsa_keygen(2048) || !ecdsa_keygen())
698 * Now handle commands that do involve connecting to a running tinc daemon.
699 * Authenticate the server by ensuring the parent directory can be
700 * traversed only by root. Note this is not totally race-free unless all
701 * ancestors are writable only by trusted users, which we don't verify.
704 FILE *f = fopen(pidfilename, "r");
706 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
709 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
710 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
715 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
716 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
721 struct addrinfo hints = {
722 .ai_family = AF_UNSPEC,
723 .ai_socktype = SOCK_STREAM,
724 .ai_protocol = IPPROTO_TCP,
728 struct addrinfo *res = NULL;
730 if(getaddrinfo(host, port, &hints, &res) || !res) {
731 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
735 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
737 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
742 unsigned long arg = 0;
744 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
745 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
749 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
750 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
758 int code, version, req;
760 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
761 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
762 sockstrerror(sockerrno));
766 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
768 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
769 fprintf(stderr, "Could not fully establish control socket connection\n");
773 if(!strcasecmp(argv[optind], "pid")) {
778 if(!strcasecmp(argv[optind], "stop")) {
780 sendline(fd, "%d %d", CONTROL, REQ_STOP);
781 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
782 fprintf(stderr, "Could not stop tinc daemon\n");
786 if(!remove_service())
792 if(!strcasecmp(argv[optind], "reload")) {
793 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
794 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
795 fprintf(stderr, "Could not reload tinc daemon\n");
801 if(!strcasecmp(argv[optind], "restart")) {
802 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
803 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
804 fprintf(stderr, "Could not restart tinc daemon\n");
810 if(!strcasecmp(argv[optind], "retry")) {
811 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
812 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
813 fprintf(stderr, "Could not retry outgoing connections\n");
819 if(!strcasecmp(argv[optind], "dump")) {
820 if(argc < optind + 2) {
821 fprintf(stderr, "Not enough arguments.\n");
826 bool do_graph = false;
828 if(!strcasecmp(argv[optind+1], "nodes"))
829 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
830 else if(!strcasecmp(argv[optind+1], "edges"))
831 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
832 else if(!strcasecmp(argv[optind+1], "subnets"))
833 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
834 else if(!strcasecmp(argv[optind+1], "connections"))
835 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
836 else if(!strcasecmp(argv[optind+1], "graph")) {
837 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
838 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
840 printf("digraph {\n");
842 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
847 while(recvline(fd, line, sizeof line)) {
848 char node1[4096], node2[4096];
849 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
851 if(do_graph && req == REQ_DUMP_NODES)
863 printf("%s\n", line + 5);
865 if(req == REQ_DUMP_NODES)
866 printf(" %s [label = \"%s\"];\n", node1, node1);
868 printf(" %s -> %s;\n", node1, node2);
872 fprintf(stderr, "Error receiving dump\n");
876 if(!strcasecmp(argv[optind], "purge")) {
877 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
878 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
879 fprintf(stderr, "Could not purge tinc daemon\n");
885 if(!strcasecmp(argv[optind], "debug")) {
886 int debuglevel, origlevel;
888 if(argc != optind + 2) {
889 fprintf(stderr, "Invalid arguments.\n");
892 debuglevel = atoi(argv[optind+1]);
894 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
895 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
896 fprintf(stderr, "Could not purge tinc daemon\n");
900 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
904 if(!strcasecmp(argv[optind], "connect")) {
905 if(argc != optind + 2) {
906 fprintf(stderr, "Invalid arguments.\n");
909 char *name = argv[optind + 1];
911 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
912 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
913 fprintf(stderr, "Could not connect to %s\n", name);
919 if(!strcasecmp(argv[optind], "disconnect")) {
920 if(argc != optind + 2) {
921 fprintf(stderr, "Invalid arguments.\n");
924 char *name = argv[optind + 1];
926 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
927 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
928 fprintf(stderr, "Could not disconnect %s\n", name);
935 if(!strcasecmp(argv[optind], "top")) {
941 if(!strcasecmp(argv[optind], "pcap")) {
942 pcap(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : 0);
946 if(!strcasecmp(argv[optind], "log")) {
947 logcontrol(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : -1);
951 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);