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.
25 #include "readline/readline.h"
26 #include "readline/history.h"
31 #include "control_common.h"
40 #define mkdir(a, b) mkdir(a)
44 /* The name this program was run with. */
45 static char *program_name = NULL;
47 static char **orig_argv;
50 /* If nonzero, display usage information and exit. */
51 static bool show_help = false;
53 /* If nonzero, print the version on standard output and exit. */
54 static bool show_version = false;
56 static char *name = NULL;
57 static char *identname = NULL; /* program name for syslog */
58 static char *pidfilename = NULL; /* pid file location */
59 static char *confdir = NULL;
60 static char controlcookie[1024];
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
66 // Horrible global variables...
69 static char line[4096];
73 static bool force = false;
74 static bool tty = true;
77 static struct WSAData wsa_state;
80 static struct option const long_options[] = {
81 {"config", required_argument, NULL, 'c'},
82 {"debug", optional_argument, NULL, 0},
83 {"no-detach", no_argument, NULL, 0},
84 {"mlock", no_argument, NULL, 0},
85 {"net", required_argument, NULL, 'n'},
86 {"help", no_argument, NULL, 1},
87 {"version", no_argument, NULL, 2},
88 {"pidfile", required_argument, NULL, 5},
89 {"logfile", required_argument, NULL, 0},
90 {"bypass-security", no_argument, NULL, 0},
91 {"chroot", no_argument, NULL, 0},
92 {"user", required_argument, NULL, 0},
93 {"option", required_argument, NULL, 0},
94 {"force", no_argument, NULL, 6},
98 static void version(void) {
99 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
100 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
101 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
102 "See the AUTHORS file for a complete list.\n\n"
103 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
104 "and you are welcome to redistribute it under certain conditions;\n"
105 "see the file COPYING for details.\n");
108 static void usage(bool status) {
110 fprintf(stderr, "Try `%s --help\' for more information.\n",
113 printf("Usage: %s [options] command\n\n", program_name);
114 printf("Valid options are:\n"
115 " -c, --config=DIR Read configuration options from DIR.\n"
116 " -n, --net=NETNAME Connect to net NETNAME.\n"
117 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
118 " --help Display this help and exit.\n"
119 " --version Output version information and exit.\n"
121 "Valid commands are:\n"
122 " init [name] Create initial configuration files.\n"
123 " config Change configuration:\n"
124 " [get] VARIABLE - print current value of VARIABLE\n"
125 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
126 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
127 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
128 " start [tincd options] Start tincd.\n"
129 " stop Stop tincd.\n"
130 " restart Restart tincd.\n"
131 " reload Partially reload configuration of running tincd.\n"
132 " pid Show PID of currently running tincd.\n"
133 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
134 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
135 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
136 " dump Dump a list of one of the following things:\n"
137 " nodes - all known nodes in the VPN\n"
138 " edges - all known connections in the VPN\n"
139 " subnets - all known subnets in the VPN\n"
140 " connections - all meta connections with ourself\n"
141 " graph - graph of the VPN in dotty format\n"
142 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
143 " purge Purge unreachable nodes\n"
144 " debug N Set debug level\n"
145 " retry Retry all outgoing connections\n"
146 " disconnect NODE Close meta connection with NODE\n"
148 " top Show real-time statistics\n"
150 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
151 " log [level] Dump log output [up to the specified level]\n"
152 " export Export host configuration of local node to standard output\n"
153 " export-all Export all host configuration files to standard output\n"
154 " import [--force] Import host configuration file(s) from standard input\n"
156 printf("Report bugs to tinc@tinc-vpn.org.\n");
160 static bool parse_options(int argc, char **argv) {
162 int option_index = 0;
164 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
166 case 0: /* long option */
169 case 'c': /* config file */
170 confbase = xstrdup(optarg);
173 case 'n': /* net name given */
174 netname = xstrdup(optarg);
177 case 1: /* show help */
181 case 2: /* show version */
185 case 5: /* open control socket here */
186 pidfilename = xstrdup(optarg);
202 if(!netname && (netname = getenv("NETNAME")))
203 netname = xstrdup(netname);
205 /* netname "." is special: a "top-level name" */
207 if(netname && (!*netname || !strcmp(netname, "."))) {
212 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
213 fprintf(stderr, "Invalid character in netname!\n");
220 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
226 /* Check stdin and stdout */
228 /* Ask for a file and/or directory name. */
229 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
233 if(fgets(buf, sizeof buf, stdin) == NULL) {
234 fprintf(stderr, "Error while reading stdin: %s\n",
239 size_t len = strlen(buf);
248 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
250 if(filename[0] != '/') {
252 /* The directory is a relative path or a filename. */
253 directory = get_current_dir_name();
254 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
258 umask(0077); /* Disallow everything for group and other */
260 /* Open it first to keep the inode busy */
262 r = fopen(filename, mode);
265 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
273 Generate a public/private ECDSA keypair, and ask for a file to store
276 static bool ecdsa_keygen(bool ask) {
281 fprintf(stderr, "Generating ECDSA keypair:\n");
283 if(!ecdsa_generate(&key)) {
284 fprintf(stderr, "Error during key generation!\n");
287 fprintf(stderr, "Done.\n");
289 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
290 f = ask_and_open(filename, "private ECDSA key", "a", ask);
296 /* Make it unreadable for others. */
297 fchmod(fileno(f), 0600);
301 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
303 ecdsa_write_pem_private_key(&key, f);
309 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
311 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
313 f = ask_and_open(filename, "public ECDSA key", "a", ask);
319 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
321 char *pubkey = ecdsa_get_base64_public_key(&key);
322 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
332 Generate a public/private RSA keypair, and ask for a file to store
335 static bool rsa_keygen(int bits, bool ask) {
340 fprintf(stderr, "Generating %d bits keys:\n", bits);
342 if(!rsa_generate(&key, bits, 0x10001)) {
343 fprintf(stderr, "Error during key generation!\n");
346 fprintf(stderr, "Done.\n");
348 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
349 f = ask_and_open(filename, "private RSA key", "a", ask);
355 /* Make it unreadable for others. */
356 fchmod(fileno(f), 0600);
360 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
362 rsa_write_pem_private_key(&key, f);
368 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
370 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
372 f = ask_and_open(filename, "public RSA key", "a", ask);
378 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
380 rsa_write_pem_public_key(&key, f);
389 Set all files and paths according to netname
391 static void make_names(void) {
394 char installdir[1024] = "";
395 long len = sizeof installdir;
399 xasprintf(&identname, "tinc.%s", netname);
401 identname = xstrdup("tinc");
404 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
405 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
408 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
410 xasprintf(&confbase, "%s", installdir);
414 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
420 confdir = xstrdup(CONFDIR);
423 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
427 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
429 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
432 xasprintf(&confbase, CONFDIR SLASH "tinc");
437 confdir = xstrdup(installdir);
440 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
441 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
444 static char buffer[4096];
445 static size_t blen = 0;
447 bool recvline(int fd, char *line, size_t len) {
448 char *newline = NULL;
450 while(!(newline = memchr(buffer, '\n', blen))) {
451 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
452 if(result == -1 && errno == EINTR)
459 if(newline - buffer >= len)
462 len = newline - buffer;
464 memcpy(line, buffer, len);
466 memmove(buffer, newline + 1, blen - len - 1);
472 static bool recvdata(int fd, char *data, size_t len) {
474 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
475 if(result == -1 && errno == EINTR)
482 memcpy(data, buffer, len);
483 memmove(buffer, buffer + len, blen - len);
489 bool sendline(int fd, char *format, ...) {
490 static char buffer[4096];
495 va_start(ap, format);
496 blen = vsnprintf(buffer, sizeof buffer, format, ap);
499 if(blen < 1 || blen >= sizeof buffer)
506 int result = send(fd, p, blen, 0);
507 if(result == -1 && errno == EINTR)
518 static void pcap(int fd, FILE *out, int snaplen) {
519 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
527 uint32_t tz_accuracy;
534 snaplen ?: sizeof data,
547 fwrite(&header, sizeof header, 1, out);
551 while(recvline(fd, line, sizeof line)) {
553 int n = sscanf(line, "%d %d %d", &code, &req, &len);
554 gettimeofday(&tv, NULL);
555 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
557 if(!recvdata(fd, data, len))
559 packet.tv_sec = tv.tv_sec;
560 packet.tv_usec = tv.tv_usec;
562 packet.origlen = len;
563 fwrite(&packet, sizeof packet, 1, out);
564 fwrite(data, len, 1, out);
569 static void logcontrol(int fd, FILE *out, int level) {
570 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
574 while(recvline(fd, line, sizeof line)) {
576 int n = sscanf(line, "%d %d %d", &code, &req, &len);
577 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
579 if(!recvdata(fd, data, len))
581 fwrite(data, len, 1, out);
588 static bool remove_service(void) {
589 SC_HANDLE manager = NULL;
590 SC_HANDLE service = NULL;
591 SERVICE_STATUS status = {0};
593 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
595 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
599 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
602 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
606 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
607 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
609 fprintf(stderr, "%s service stopped\n", identname);
611 if(!DeleteService(service)) {
612 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
616 fprintf(stderr, "%s service removed\n", identname);
622 static bool connect_tincd(bool verbose) {
626 FILE *f = fopen(pidfilename, "r");
629 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
636 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
638 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
646 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
648 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
653 struct addrinfo hints = {
654 .ai_family = AF_UNSPEC,
655 .ai_socktype = SOCK_STREAM,
656 .ai_protocol = IPPROTO_TCP,
660 struct addrinfo *res = NULL;
662 if(getaddrinfo(host, port, &hints, &res) || !res) {
664 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
668 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
671 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
676 unsigned long arg = 0;
678 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
680 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
684 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
686 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
695 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
697 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
701 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
703 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
705 fprintf(stderr, "Could not fully establish control socket connection\n");
713 static int cmd_start(int argc, char *argv[]) {
714 if(connect_tincd(false)) {
716 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
718 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
723 char *slash = strrchr(program_name, '/');
726 if ((c = strrchr(program_name, '\\')) > slash)
731 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
736 char **nargv = xmalloc_and_zero((orig_argc + argc) * sizeof *nargv);
738 for(int i = 0; i < orig_argc; i++)
739 nargv[nargc++] = orig_argv[i];
740 for(int i = 1; i < argc; i++)
741 nargv[nargc++] = argv[i];
745 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
750 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
755 exit(execvp(c, nargv));
758 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
759 fprintf(stderr, "Error starting %s\n", c);
767 static int cmd_stop(int argc, char *argv[]) {
769 if(!connect_tincd(true)) {
771 if(kill(pid, SIGTERM))
773 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
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())
796 static int cmd_restart(int argc, char *argv[]) {
797 cmd_stop(argc, argv);
798 return cmd_start(argc, argv);
801 static int cmd_reload(int argc, char *argv[]) {
802 if(!connect_tincd(true))
805 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
806 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
807 fprintf(stderr, "Could not reload configuration.\n");
815 static int cmd_dump(int argc, char *argv[]) {
817 fprintf(stderr, "Invalid number of arguments.\n");
822 if(!connect_tincd(true))
825 bool do_graph = false;
827 if(!strcasecmp(argv[1], "nodes"))
828 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
829 else if(!strcasecmp(argv[1], "edges"))
830 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
831 else if(!strcasecmp(argv[1], "subnets"))
832 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
833 else if(!strcasecmp(argv[1], "connections"))
834 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
835 else if(!strcasecmp(argv[1], "graph")) {
836 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
837 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
840 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
846 printf("digraph {\n");
848 while(recvline(fd, line, sizeof line)) {
849 char node1[4096], node2[4096];
850 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
852 if(do_graph && req == REQ_DUMP_NODES)
872 int cipher, digest, maclength, compression, distance, socket, weight;
873 short int pmtu, minmtu, maxmtu;
874 unsigned int options, status;
875 long int last_state_change;
878 case REQ_DUMP_NODES: {
879 int n = sscanf(line, "%*d %*d %s %s port %s %d %d %d %d %x %x %s %s %d %hd %hd %hd %ld", node, host, port, &cipher, &digest, &maclength, &compression, &options, &status, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change);
881 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
884 printf("%s at %s port %s cipher %d digest %d maclength %d compression %d options %x status %04x nexthop %s via %s distance %d pmtu %hd (min %hd max %hd)\n",
885 node, host, port, cipher, digest, maclength, compression, options, status, nexthop, via, distance, pmtu, minmtu, maxmtu);
888 case REQ_DUMP_EDGES: {
889 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
891 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
894 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
897 case REQ_DUMP_SUBNETS: {
898 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
900 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
903 printf("%s owner %s\n", strip_weight(subnet), node);
906 case REQ_DUMP_CONNECTIONS: {
907 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status);
909 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
912 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status);
916 fprintf(stderr, "Unable to parse dump from tincd.\n");
920 if(req == REQ_DUMP_NODES)
921 printf(" %s [label = \"%s\"];\n", node1, node1);
923 printf(" %s -> %s;\n", node1, node2);
927 fprintf(stderr, "Error receiving dump.\n");
931 static int cmd_purge(int argc, char *argv[]) {
932 if(!connect_tincd(true))
935 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
936 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
937 fprintf(stderr, "Could not purge old information.\n");
944 static int cmd_debug(int argc, char *argv[]) {
946 fprintf(stderr, "Invalid number of arguments.\n");
950 if(!connect_tincd(true))
953 int debuglevel = atoi(argv[1]);
956 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
957 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
958 fprintf(stderr, "Could not set debug level.\n");
962 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
966 static int cmd_retry(int argc, char *argv[]) {
967 if(!connect_tincd(true))
970 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
971 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
972 fprintf(stderr, "Could not retry outgoing connections.\n");
979 static int cmd_connect(int argc, char *argv[]) {
981 fprintf(stderr, "Invalid number of arguments.\n");
985 if(!check_id(argv[1])) {
986 fprintf(stderr, "Invalid name for node.\n");
990 if(!connect_tincd(true))
993 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
994 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
995 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1002 static int cmd_disconnect(int argc, char *argv[]) {
1004 fprintf(stderr, "Invalid number of arguments.\n");
1008 if(!check_id(argv[1])) {
1009 fprintf(stderr, "Invalid name for node.\n");
1013 if(!connect_tincd(true))
1016 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1017 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1018 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1025 static int cmd_top(int argc, char *argv[]) {
1027 if(!connect_tincd(true))
1033 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1038 static int cmd_pcap(int argc, char *argv[]) {
1039 if(!connect_tincd(true))
1042 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1046 static int cmd_log(int argc, char *argv[]) {
1047 if(!connect_tincd(true))
1050 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1054 static int cmd_pid(int argc, char *argv[]) {
1055 if(!connect_tincd(true) && !pid)
1058 printf("%d\n", pid);
1062 static int rstrip(char *value) {
1063 int len = strlen(value);
1064 while(len && strchr("\t\r\n ", value[len - 1]))
1069 static char *get_my_name() {
1070 FILE *f = fopen(tinc_conf, "r");
1072 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1078 while(fgets(buf, sizeof buf, f)) {
1079 int len = strcspn(buf, "\t =");
1081 value += strspn(value, "\t ");
1084 value += strspn(value, "\t ");
1089 if(strcasecmp(buf, "Name"))
1093 return strdup(value);
1098 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1102 #define VAR_SERVER 1 /* Should be in tinc.conf */
1103 #define VAR_HOST 2 /* Can be in host config file */
1104 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1105 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1110 } const variables[] = {
1111 /* Server configuration */
1112 {"AddressFamily", VAR_SERVER},
1113 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1114 {"BindToInterface", VAR_SERVER},
1115 {"Broadcast", VAR_SERVER},
1116 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1117 {"DecrementTTL", VAR_SERVER},
1118 {"Device", VAR_SERVER},
1119 {"DeviceType", VAR_SERVER},
1120 {"DirectOnly", VAR_SERVER},
1121 {"ECDSAPrivateKeyFile", VAR_SERVER},
1122 {"ExperimentalProtocol", VAR_SERVER},
1123 {"Forwarding", VAR_SERVER},
1124 {"GraphDumpFile", VAR_SERVER},
1125 {"Hostnames", VAR_SERVER},
1126 {"IffOneQueue", VAR_SERVER},
1127 {"Interface", VAR_SERVER},
1128 {"KeyExpire", VAR_SERVER},
1129 {"LocalDiscovery", VAR_SERVER},
1130 {"MACExpire", VAR_SERVER},
1131 {"MaxOutputBufferSize", VAR_SERVER},
1132 {"MaxTimeout", VAR_SERVER},
1133 {"Mode", VAR_SERVER},
1134 {"Name", VAR_SERVER},
1135 {"PingInterval", VAR_SERVER},
1136 {"PingTimeout", VAR_SERVER},
1137 {"PriorityInheritance", VAR_SERVER},
1138 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1139 {"PrivateKeyFile", VAR_SERVER},
1140 {"ProcessPriority", VAR_SERVER},
1141 {"Proxy", VAR_SERVER},
1142 {"ReplayWindow", VAR_SERVER},
1143 {"StrictSubnets", VAR_SERVER},
1144 {"TunnelServer", VAR_SERVER},
1145 {"UDPRcvBuf", VAR_SERVER},
1146 {"UDPSndBuf", VAR_SERVER},
1147 {"VDEGroup", VAR_SERVER},
1148 {"VDEPort", VAR_SERVER},
1149 /* Host configuration */
1150 {"Address", VAR_HOST | VAR_MULTIPLE},
1151 {"Cipher", VAR_SERVER | VAR_HOST},
1152 {"ClampMSS", VAR_SERVER | VAR_HOST},
1153 {"Compression", VAR_SERVER | VAR_HOST},
1154 {"Digest", VAR_SERVER | VAR_HOST},
1155 {"ECDSAPublicKey", VAR_HOST},
1156 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1157 {"IndirectData", VAR_SERVER | VAR_HOST},
1158 {"MACLength", VAR_SERVER | VAR_HOST},
1159 {"PMTU", VAR_SERVER | VAR_HOST},
1160 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1162 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1163 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1164 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1165 {"TCPOnly", VAR_SERVER | VAR_HOST},
1166 {"Weight", VAR_HOST},
1170 static int cmd_config(int argc, char *argv[]) {
1172 fprintf(stderr, "Invalid number of arguments.\n");
1177 if(!strcasecmp(argv[1], "get")) {
1179 } else if(!strcasecmp(argv[1], "add")) {
1180 argv++, argc--, action = 1;
1181 } else if(!strcasecmp(argv[1], "del")) {
1182 argv++, argc--, action = -1;
1183 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1184 argv++, argc--, action = 0;
1188 fprintf(stderr, "Invalid number of arguments.\n");
1192 // Concatenate the rest of the command line
1193 strncpy(line, argv[1], sizeof line - 1);
1194 for(int i = 2; i < argc; i++) {
1195 strncat(line, " ", sizeof line - 1 - strlen(line));
1196 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1199 // Liberal parsing into node name, variable name and value.
1205 len = strcspn(line, "\t =");
1207 value += strspn(value, "\t ");
1210 value += strspn(value, "\t ");
1213 variable = strchr(line, '.');
1222 fprintf(stderr, "No variable given.\n");
1226 if(action >= 0 && !*value) {
1227 fprintf(stderr, "No value for variable given.\n");
1231 if(action < -1 && *value)
1234 /* Some simple checks. */
1237 for(int i = 0; variables[i].name; i++) {
1238 if(strcasecmp(variables[i].name, variable))
1242 variable = (char *)variables[i].name;
1244 /* Discourage use of obsolete variables. */
1246 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1248 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1250 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1255 /* Don't put server variables in host config files */
1257 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1259 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1261 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1266 /* Should this go into our own host config file? */
1268 if(!node && !(variables[i].type & VAR_SERVER)) {
1269 node = get_my_name();
1277 if(node && !check_id(node)) {
1278 fprintf(stderr, "Invalid name for node.\n");
1283 if(force || action < 0) {
1284 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1286 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1291 // Open the right configuration file.
1294 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1296 filename = tinc_conf;
1298 FILE *f = fopen(filename, "r");
1300 if(action < 0 || errno != ENOENT) {
1301 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1305 // If it doesn't exist, create it.
1306 f = fopen(filename, "a+");
1308 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1311 fprintf(stderr, "Created configuration file %s.\n", filename);
1315 char *tmpfile = NULL;
1319 xasprintf(&tmpfile, "%s.config.tmp", filename);
1320 tf = fopen(tmpfile, "w");
1322 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1328 // Copy the file, making modifications on the fly, unless we are just getting a value.
1332 bool removed = false;
1335 while(fgets(buf1, sizeof buf1, f)) {
1336 buf1[sizeof buf1 - 1] = 0;
1337 strncpy(buf2, buf1, sizeof buf2);
1339 // Parse line in a simple way
1343 len = strcspn(buf2, "\t =");
1344 bvalue = buf2 + len;
1345 bvalue += strspn(bvalue, "\t ");
1346 if(*bvalue == '=') {
1348 bvalue += strspn(bvalue, "\t ");
1354 if(!strcasecmp(buf2, variable)) {
1358 printf("%s\n", bvalue);
1360 } else if(action == -1) {
1361 if(!*value || !strcasecmp(bvalue, value)) {
1366 } else if(action == 0) {
1367 // Already set? Delete the rest...
1370 // Otherwise, replace.
1371 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1372 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1381 // Copy original line...
1382 if(fputs(buf1, tf) < 0) {
1383 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1387 // Add newline if it is missing...
1388 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1389 if(fputc('\n', tf) < 0) {
1390 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1397 // Make sure we read everything...
1398 if(ferror(f) || !feof(f)) {
1399 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1404 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1408 // Add new variable if necessary.
1409 if(action > 0 || (action == 0 && !set)) {
1410 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1411 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1418 fprintf(stderr, "No matching configuration variables found.\n");
1422 // Make sure we wrote everything...
1424 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1428 // Could we find what we had to remove?
1429 if(action < 0 && !removed) {
1431 fprintf(stderr, "No configuration variables deleted.\n");
1435 // Replace the configuration file with the new one
1437 if(remove(filename)) {
1438 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1442 if(rename(tmpfile, filename)) {
1443 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1447 // Silently try notifying a running tincd of changes.
1448 if(connect_tincd(false))
1449 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1454 bool check_id(const char *name) {
1458 for(int i = 0; i < strlen(name); i++) {
1459 if(!isalnum(name[i]) && name[i] != '_')
1466 static int cmd_init(int argc, char *argv[]) {
1467 if(!access(tinc_conf, F_OK)) {
1468 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1475 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1477 if(!fgets(buf, sizeof buf, stdin)) {
1478 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1481 int len = rstrip(buf);
1483 fprintf(stderr, "No name given!\n");
1488 fprintf(stderr, "No Name given!\n");
1492 name = strdup(argv[1]);
1494 fprintf(stderr, "No Name given!\n");
1499 if(!check_id(name)) {
1500 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1504 if(mkdir(confdir, 0755) && errno != EEXIST) {
1505 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1509 if(mkdir(confbase, 0755) && errno != EEXIST) {
1510 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1514 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1515 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1519 FILE *f = fopen(tinc_conf, "w");
1521 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1525 fprintf(f, "Name = %s\n", name);
1528 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1533 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1534 if(access(filename, F_OK)) {
1535 FILE *f = fopen(filename, "w");
1537 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1540 fchmod(fileno(f), 0755);
1541 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1550 static int cmd_generate_keys(int argc, char *argv[]) {
1551 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1554 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1555 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1558 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1559 return !ecdsa_keygen(true);
1562 static int cmd_help(int argc, char *argv[]) {
1567 static int cmd_version(int argc, char *argv[]) {
1572 static int cmd_info(int argc, char *argv[]) {
1574 fprintf(stderr, "Invalid number of arguments.\n");
1578 if(!connect_tincd(true))
1581 return info(fd, argv[1]);
1584 static const char *conffiles[] = {
1595 static int cmd_edit(int argc, char *argv[]) {
1597 fprintf(stderr, "Invalid number of arguments.\n");
1601 char *filename = NULL;
1603 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1604 for(int i = 0; conffiles[i]; i++) {
1605 if(!strcmp(argv[1], conffiles[i])) {
1606 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1615 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1616 char *dash = strchr(argv[1], '-');
1619 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1620 fprintf(stderr, "Invalid configuration filename.\n");
1628 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1630 xasprintf(&command, "edit \"%s\"", filename);
1632 int result = system(command);
1636 // Silently try notifying a running tincd of changes.
1637 if(connect_tincd(false))
1638 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1643 static int export(const char *name, FILE *out) {
1645 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1646 FILE *in = fopen(filename, "r");
1648 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1652 fprintf(out, "Name = %s\n", name);
1654 while(fgets(buf, sizeof buf, in)) {
1655 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1660 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1669 static int cmd_export(int argc, char *argv[]) {
1670 char *name = get_my_name();
1674 return export(name, stdout);
1677 static int cmd_export_all(int argc, char *argv[]) {
1678 DIR *dir = opendir(hosts_dir);
1680 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1688 while((ent = readdir(dir))) {
1689 if(!check_id(ent->d_name))
1695 printf("#---------------------------------------------------------------#\n");
1697 result |= export(ent->d_name, stdout);
1704 static int cmd_import(int argc, char *argv[]) {
1712 bool firstline = true;
1714 while(fgets(buf, sizeof buf, in)) {
1715 if(sscanf(buf, "Name = %s", name) == 1) {
1716 if(!check_id(name)) {
1717 fprintf(stderr, "Invalid Name in input!\n");
1725 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1727 if(!force && !access(filename, F_OK)) {
1728 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1733 out = fopen(filename, "w");
1735 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1742 } else if(firstline) {
1743 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1748 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1752 if(fputs(buf, out) < 0) {
1753 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1763 fprintf(stderr, "Imported %d host configuration files.\n", count);
1766 fprintf(stderr, "No host configuration files imported.\n");
1771 static const struct {
1772 const char *command;
1773 int (*function)(int argc, char *argv[]);
1775 {"start", cmd_start},
1777 {"restart", cmd_restart},
1778 {"reload", cmd_reload},
1780 {"purge", cmd_purge},
1781 {"debug", cmd_debug},
1782 {"retry", cmd_retry},
1783 {"connect", cmd_connect},
1784 {"disconnect", cmd_disconnect},
1789 {"config", cmd_config},
1791 {"generate-keys", cmd_generate_keys},
1792 {"generate-rsa-keys", cmd_generate_rsa_keys},
1793 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1795 {"version", cmd_version},
1798 {"export", cmd_export},
1799 {"export-all", cmd_export_all},
1800 {"import", cmd_import},
1804 #ifdef HAVE_READLINE
1805 static char *complete_command(const char *text, int state) {
1813 while(commands[i].command) {
1814 if(!strncasecmp(commands[i].command, text, strlen(text)))
1815 return xstrdup(commands[i].command);
1822 static char *complete_dump(const char *text, int state) {
1823 const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1832 if(!strncasecmp(matches[i], text, strlen(text)))
1833 return xstrdup(matches[i]);
1840 static char *complete_config(const char *text, int state) {
1841 const char *sub[] = {"get", "set", "add", "del"};
1845 if(!strchr(rl_line_buffer + 7, ' '))
1849 for(int i = 0; i < 4; i++) {
1850 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1862 while(i < 0 || variables[i].name) {
1863 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
1864 return xstrdup(sub[i + 4]);
1866 char *dot = strchr(text, '.');
1868 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
1870 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
1874 if(!strncasecmp(variables[i].name, text, strlen(text)))
1875 return xstrdup(variables[i].name);
1884 static char *complete_info(const char *text, int state) {
1888 if(!connect_tincd(false))
1890 // Check the list of nodes
1891 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
1892 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
1895 while(recvline(fd, line, sizeof line)) {
1897 int n = sscanf(line, "%d %d %s", &code, &req, item);
1907 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
1911 if(!strncmp(item, text, strlen(text)))
1912 return xstrdup(strip_weight(item));
1918 static char *complete_nothing(const char *text, int state) {
1922 static char **completion (const char *text, int start, int end) {
1923 char **matches = NULL;
1926 matches = rl_completion_matches(text, complete_command);
1927 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
1928 matches = rl_completion_matches(text, complete_dump);
1929 else if(!strncasecmp(rl_line_buffer, "config ", 7))
1930 matches = rl_completion_matches(text, complete_config);
1931 else if(!strncasecmp(rl_line_buffer, "info ", 5))
1932 matches = rl_completion_matches(text, complete_info);
1938 static int cmd_shell(int argc, char *argv[]) {
1940 xasprintf(&prompt, "%s> ", identname);
1944 int maxargs = argc + 16;
1945 char **nargv = xmalloc(maxargs * sizeof *nargv);
1948 for(int i = 0; i < argc; i++)
1951 #ifdef HAVE_READLINE
1952 rl_readline_name = "tinc";
1953 rl_completion_entry_function = complete_nothing;
1954 rl_attempted_completion_function = completion;
1955 rl_filename_completion_desired = 0;
1960 #ifdef HAVE_READLINE
1964 rl_basic_word_break_characters = "\t\n ";
1965 line = readline(prompt);
1967 copy = xstrdup(line);
1969 line = fgets(buf, sizeof buf, stdin);
1973 fputs(prompt, stdout);
1975 line = fgets(buf, sizeof buf, stdin);
1981 /* Ignore comments */
1989 char *p = line + strspn(line, " \t\n");
1990 char *next = strtok(p, " \t\n");
1993 if(nargc >= maxargs) {
1994 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
1997 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2002 next = strtok(NULL, " \t\n");
2008 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2013 for(int i = 0; commands[i].command; i++) {
2014 if(!strcasecmp(nargv[argc], commands[i].command)) {
2015 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2021 #ifdef HAVE_READLINE
2027 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2038 int main(int argc, char *argv[]) {
2039 program_name = argv[0];
2043 if(!parse_options(argc, argv))
2058 tty = isatty(0) && isatty(1);
2061 return cmd_shell(argc, argv);
2063 for(int i = 0; commands[i].command; i++) {
2064 if(!strcasecmp(argv[optind], commands[i].command))
2065 return commands[i].function(argc - optind, argv + optind);
2068 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);