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;
49 // Horrible global variables...
52 static char line[4096];
58 static struct WSAData wsa_state;
61 static struct option const long_options[] = {
62 {"config", required_argument, NULL, 'c'},
63 {"net", required_argument, NULL, 'n'},
64 {"help", no_argument, NULL, 1},
65 {"version", no_argument, NULL, 2},
66 {"pidfile", required_argument, NULL, 5},
70 static void version(void) {
71 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
72 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
73 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
74 "See the AUTHORS file for a complete list.\n\n"
75 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
76 "and you are welcome to redistribute it under certain conditions;\n"
77 "see the file COPYING for details.\n");
80 static void usage(bool status) {
82 fprintf(stderr, "Try `%s --help\' for more information.\n",
85 printf("Usage: %s [options] command\n\n", program_name);
86 printf("Valid options are:\n"
87 " -c, --config=DIR Read configuration options from DIR.\n"
88 " -n, --net=NETNAME Connect to net NETNAME.\n"
89 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
90 " --help Display this help and exit.\n"
91 " --version Output version information and exit.\n"
93 "Valid commands are:\n"
94 " init [name] Create initial configuration files.\n"
95 " start Start tincd.\n"
97 " restart Restart tincd.\n"
98 " reload Partially reload configuration of running tincd.\n"
99 " pid Show PID of currently running tincd.\n"
100 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
101 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
102 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
103 " dump Dump a list of one of the following things:\n"
104 " nodes - all known nodes in the VPN\n"
105 " edges - all known connections in the VPN\n"
106 " subnets - all known subnets in the VPN\n"
107 " connections - all meta connections with ourself\n"
108 " graph - graph of the VPN in dotty format\n"
109 " purge Purge unreachable nodes\n"
110 " debug N Set debug level\n"
111 " retry Retry all outgoing connections\n"
112 " disconnect NODE Close meta connection with NODE\n"
114 " top Show real-time statistics\n"
116 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
117 " log [level] Dump log output [up to the specified level]\n"
119 printf("Report bugs to tinc@tinc-vpn.org.\n");
123 static bool parse_options(int argc, char **argv) {
125 int option_index = 0;
127 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
129 case 0: /* long option */
132 case 'c': /* config file */
133 confbase = xstrdup(optarg);
136 case 'n': /* net name given */
137 netname = xstrdup(optarg);
140 case 1: /* show help */
144 case 2: /* show version */
148 case 5: /* open control socket here */
149 pidfilename = xstrdup(optarg);
162 netname = getenv("NETNAME");
164 netname = xstrdup(netname);
170 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
176 /* Check stdin and stdout */
177 if(isatty(0) && isatty(1)) {
178 /* Ask for a file and/or directory name. */
179 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
183 if(fgets(buf, sizeof buf, stdin) == NULL) {
184 fprintf(stderr, "Error while reading stdin: %s\n",
189 size_t len = strlen(buf);
198 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
200 if(filename[0] != '/') {
202 /* The directory is a relative path or a filename. */
203 directory = get_current_dir_name();
204 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
208 umask(0077); /* Disallow everything for group and other */
210 /* Open it first to keep the inode busy */
212 r = fopen(filename, mode);
215 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
223 Generate a public/private ECDSA keypair, and ask for a file to store
226 static bool ecdsa_keygen() {
231 fprintf(stderr, "Generating ECDSA keypair:\n");
233 if(!ecdsa_generate(&key)) {
234 fprintf(stderr, "Error during key generation!\n");
237 fprintf(stderr, "Done.\n");
239 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
240 f = ask_and_open(filename, "private ECDSA key", "a");
246 /* Make it unreadable for others. */
247 fchmod(fileno(f), 0600);
251 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
253 ecdsa_write_pem_private_key(&key, f);
259 xasprintf(&filename, "%s/hosts/%s", confbase, name);
261 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
263 f = ask_and_open(filename, "public ECDSA key", "a");
269 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
271 char *pubkey = ecdsa_get_base64_public_key(&key);
272 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
282 Generate a public/private RSA keypair, and ask for a file to store
285 static bool rsa_keygen(int bits) {
290 fprintf(stderr, "Generating %d bits keys:\n", bits);
292 if(!rsa_generate(&key, bits, 0x10001)) {
293 fprintf(stderr, "Error during key generation!\n");
296 fprintf(stderr, "Done.\n");
298 xasprintf(&filename, "%s/rsa_key.priv", confbase);
299 f = ask_and_open(filename, "private RSA key", "a");
305 /* Make it unreadable for others. */
306 fchmod(fileno(f), 0600);
310 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
312 rsa_write_pem_private_key(&key, f);
318 xasprintf(&filename, "%s/hosts/%s", confbase, name);
320 xasprintf(&filename, "%s/rsa_key.pub", confbase);
322 f = ask_and_open(filename, "public RSA key", "a");
328 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
330 rsa_write_pem_public_key(&key, f);
339 Set all files and paths according to netname
341 static void make_names(void) {
344 char installdir[1024] = "";
345 long len = sizeof installdir;
349 xasprintf(&identname, "tinc.%s", netname);
351 identname = xstrdup("tinc");
354 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
355 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
358 xasprintf(&confbase, "%s/%s", installdir, netname);
360 xasprintf(&confbase, "%s", installdir);
364 xasprintf(&pidfilename, "%s/pid", confbase);
372 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
376 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
378 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
381 xasprintf(&confbase, CONFDIR "/tinc");
385 static char buffer[4096];
386 static size_t blen = 0;
388 bool recvline(int fd, char *line, size_t len) {
389 char *newline = NULL;
391 while(!(newline = memchr(buffer, '\n', blen))) {
392 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
393 if(result == -1 && errno == EINTR)
400 if(newline - buffer >= len)
403 len = newline - buffer;
405 memcpy(line, buffer, len);
407 memmove(buffer, newline + 1, blen - len - 1);
413 static bool recvdata(int fd, char *data, size_t len) {
415 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
416 if(result == -1 && errno == EINTR)
423 memcpy(data, buffer, len);
424 memmove(buffer, buffer + len, blen - len);
430 bool sendline(int fd, char *format, ...) {
431 static char buffer[4096];
436 va_start(ap, format);
437 blen = vsnprintf(buffer, sizeof buffer, format, ap);
440 if(blen < 1 || blen >= sizeof buffer)
447 int result = send(fd, p, blen, 0);
448 if(result == -1 && errno == EINTR)
459 static void pcap(int fd, FILE *out, int snaplen) {
460 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
468 uint32_t tz_accuracy;
475 snaplen ?: sizeof data,
488 fwrite(&header, sizeof header, 1, out);
492 while(recvline(fd, line, sizeof line)) {
494 int n = sscanf(line, "%d %d %d", &code, &req, &len);
495 gettimeofday(&tv, NULL);
496 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
498 if(!recvdata(fd, data, len))
500 packet.tv_sec = tv.tv_sec;
501 packet.tv_usec = tv.tv_usec;
503 packet.origlen = len;
504 fwrite(&packet, sizeof packet, 1, out);
505 fwrite(data, len, 1, out);
510 static void logcontrol(int fd, FILE *out, int level) {
511 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
515 while(recvline(fd, line, sizeof line)) {
517 int n = sscanf(line, "%d %d %d", &code, &req, &len);
518 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
520 if(!recvdata(fd, data, len))
522 fwrite(data, len, 1, out);
529 static bool remove_service(void) {
530 SC_HANDLE manager = NULL;
531 SC_HANDLE service = NULL;
532 SERVICE_STATUS status = {0};
534 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
536 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
540 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
543 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
547 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
548 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
550 fprintf(stderr, "%s service stopped\n", identname);
552 if(!DeleteService(service)) {
553 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
557 fprintf(stderr, "%s service removed\n", identname);
563 static bool connect_tincd() {
567 FILE *f = fopen(pidfilename, "r");
569 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
576 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
577 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
582 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
583 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
588 struct addrinfo hints = {
589 .ai_family = AF_UNSPEC,
590 .ai_socktype = SOCK_STREAM,
591 .ai_protocol = IPPROTO_TCP,
595 struct addrinfo *res = NULL;
597 if(getaddrinfo(host, port, &hints, &res) || !res) {
598 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
602 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
604 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
609 unsigned long arg = 0;
611 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
612 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
616 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
617 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
626 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
627 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
631 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
633 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
634 fprintf(stderr, "Could not fully establish control socket connection\n");
642 static int cmd_start(int argc, char *argv[]) {
645 char *slash = strrchr(argv[0], '/');
648 if ((c = strrchr(argv[0], '\\')) > slash)
653 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
654 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
661 for(i = j = 1; argv[i]; ++i)
662 if (i != optind && strcmp(argv[i], "--") != 0)
667 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
671 static int cmd_stop(int argc, char *argv[]) {
676 sendline(fd, "%d %d", CONTROL, REQ_STOP);
677 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
678 fprintf(stderr, "Could not stop tinc daemon.\n");
682 if(!remove_service())
688 static int cmd_restart(int argc, char *argv[]) {
689 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
692 static int cmd_reload(int argc, char *argv[]) {
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 configuration.\n");
706 static int cmd_dump(int argc, char *argv[]) {
708 fprintf(stderr, "Invalid number of arguments.\n");
713 bool do_graph = false;
715 if(!strcasecmp(argv[1], "nodes"))
716 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
717 else if(!strcasecmp(argv[1], "edges"))
718 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
719 else if(!strcasecmp(argv[1], "subnets"))
720 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
721 else if(!strcasecmp(argv[1], "connections"))
722 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
723 else if(!strcasecmp(argv[1], "graph")) {
724 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
725 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
728 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
737 printf("digraph {\n");
739 while(recvline(fd, line, sizeof line)) {
740 char node1[4096], node2[4096];
741 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
743 if(do_graph && req == REQ_DUMP_NODES)
755 printf("%s\n", line + 5);
757 if(req == REQ_DUMP_NODES)
758 printf(" %s [label = \"%s\"];\n", node1, node1);
760 printf(" %s -> %s;\n", node1, node2);
764 fprintf(stderr, "Error receiving dump.\n");
768 static int cmd_purge(int argc, char *argv[]) {
772 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
773 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
774 fprintf(stderr, "Could not purge old information.\n");
781 static int cmd_debug(int argc, char *argv[]) {
783 fprintf(stderr, "Invalid number of arguments.\n");
790 int debuglevel = atoi(argv[1]);
793 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
794 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
795 fprintf(stderr, "Could not set debug level.\n");
799 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
803 static int cmd_retry(int argc, char *argv[]) {
807 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
808 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
809 fprintf(stderr, "Could not retry outgoing connections.\n");
816 static int cmd_connect(int argc, char *argv[]) {
818 fprintf(stderr, "Invalid number of arguments.\n");
825 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
826 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
827 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
834 static int cmd_disconnect(int argc, char *argv[]) {
836 fprintf(stderr, "Invalid number of arguments.\n");
843 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
844 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
845 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
852 static int cmd_top(int argc, char *argv[]) {
860 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
865 static int cmd_pcap(int argc, char *argv[]) {
869 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
873 static int cmd_log(int argc, char *argv[]) {
877 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
881 static int cmd_pid(int argc, char *argv[]) {
889 static int cmd_init(int argc, char *argv[]) {
890 char *tinc_conf = NULL;
891 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
892 if(!access(confbase, F_OK)) {
893 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
897 if(optind >= argc - 1) {
898 if(isatty(0) && isatty(1)) {
900 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
902 if(!fgets(buf, sizeof buf, stdin)) {
903 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
906 int len = strlen(buf);
910 fprintf(stderr, "No name given!\n");
915 fprintf(stderr, "No Name given!\n");
919 name = strdup(argv[optind + 1]);
921 fprintf(stderr, "No Name given!\n");
926 for(int i = 0; i < strlen(name); i++) {
927 if(!isalnum(name[i]) && name[i] != '_') {
928 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
933 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
934 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
938 if(mkdir(confbase, 0755) && errno != EEXIST) {
939 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
943 char *hosts_dir = NULL;
944 xasprintf(&hosts_dir, "%s/hosts", confbase);
945 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
946 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
950 FILE *f = fopen(tinc_conf, "w");
952 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
956 fprintf(f, "Name = %s\n", name);
960 if(!rsa_keygen(2048) || !ecdsa_keygen())
967 static int cmd_generate_keys(int argc, char *argv[]) {
968 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
971 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
972 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
975 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
976 return !ecdsa_keygen();
979 static int cmd_help(int argc, char *argv[]) {
984 static int cmd_version(int argc, char *argv[]) {
989 static const struct {
991 int (*function)(int argc, char *argv[]);
993 {"start", cmd_start},
995 {"restart", cmd_restart},
996 {"reload", cmd_reload},
998 {"purge", cmd_purge},
999 {"debug", cmd_debug},
1000 {"retry", cmd_retry},
1001 {"connect", cmd_connect},
1002 {"disconnect", cmd_disconnect},
1008 {"generate-keys", cmd_generate_keys},
1009 {"generate-rsa-keys", cmd_generate_rsa_keys},
1010 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1012 {"version", cmd_version},
1016 int main(int argc, char *argv[]) {
1017 program_name = argv[0];
1019 if(!parse_options(argc, argv))
1034 if(optind >= argc) {
1035 fprintf(stderr, "No command given.\n");
1040 for(int i = 0; commands[i].command; i++) {
1041 if(!strcasecmp(argv[optind], commands[i].command))
1042 return commands[i].function(argc - optind, argv + optind);
1045 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);