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[1025];
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
67 // Horrible global variables...
70 static char line[4096];
74 static bool force = false;
75 static bool tty = true;
78 static struct WSAData wsa_state;
81 static struct option const long_options[] = {
82 {"config", required_argument, NULL, 'c'},
83 {"debug", optional_argument, NULL, 0},
84 {"no-detach", no_argument, NULL, 0},
85 {"mlock", no_argument, NULL, 0},
86 {"net", required_argument, NULL, 'n'},
87 {"help", no_argument, NULL, 1},
88 {"version", no_argument, NULL, 2},
89 {"pidfile", required_argument, NULL, 5},
90 {"logfile", required_argument, NULL, 0},
91 {"bypass-security", no_argument, NULL, 0},
92 {"chroot", no_argument, NULL, 0},
93 {"user", required_argument, NULL, 0},
94 {"option", required_argument, NULL, 0},
95 {"force", no_argument, NULL, 6},
99 static void version(void) {
100 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
101 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
102 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
103 "See the AUTHORS file for a complete list.\n\n"
104 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
105 "and you are welcome to redistribute it under certain conditions;\n"
106 "see the file COPYING for details.\n");
109 static void usage(bool status) {
111 fprintf(stderr, "Try `%s --help\' for more information.\n",
114 printf("Usage: %s [options] command\n\n", program_name);
115 printf("Valid options are:\n"
116 " -c, --config=DIR Read configuration options from DIR.\n"
117 " -n, --net=NETNAME Connect to net NETNAME.\n"
118 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
119 " --help Display this help and exit.\n"
120 " --version Output version information and exit.\n"
122 "Valid commands are:\n"
123 " init [name] Create initial configuration files.\n"
124 " config Change configuration:\n"
125 " [get] VARIABLE - print current value of VARIABLE\n"
126 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
127 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
128 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
129 " start [tincd options] Start tincd.\n"
130 " stop Stop tincd.\n"
131 " restart Restart tincd.\n"
132 " reload Partially reload configuration of running tincd.\n"
133 " pid Show PID of currently running tincd.\n"
134 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
135 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
136 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
137 " dump Dump a list of one of the following things:\n"
138 " [reachable] nodes - all known nodes in the VPN\n"
139 " edges - all known connections in the VPN\n"
140 " subnets - all known subnets in the VPN\n"
141 " connections - all meta connections with ourself\n"
142 " [di]graph - graph of the VPN in dotty format\n"
143 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
144 " purge Purge unreachable nodes\n"
145 " debug N Set debug level\n"
146 " retry Retry all outgoing connections\n"
147 " disconnect NODE Close meta connection with NODE\n"
149 " top Show real-time statistics\n"
151 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
152 " log [level] Dump log output [up to the specified level]\n"
153 " export Export host configuration of local node to standard output\n"
154 " export-all Export all host configuration files to standard output\n"
155 " import [--force] Import host configuration file(s) from standard input\n"
156 " exchange [--force] Same as export followed by import\n"
157 " exchange-all [--force] Same as export-all followed by import\n"
159 printf("Report bugs to tinc@tinc-vpn.org.\n");
163 static bool parse_options(int argc, char **argv) {
165 int option_index = 0;
167 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
169 case 0: /* long option */
172 case 'c': /* config file */
173 confbase = xstrdup(optarg);
176 case 'n': /* net name given */
177 netname = xstrdup(optarg);
180 case 1: /* show help */
184 case 2: /* show version */
188 case 5: /* open control socket here */
189 pidfilename = xstrdup(optarg);
196 case '?': /* wrong options */
205 if(!netname && (netname = getenv("NETNAME")))
206 netname = xstrdup(netname);
208 /* netname "." is special: a "top-level name" */
210 if(netname && (!*netname || !strcmp(netname, "."))) {
215 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
216 fprintf(stderr, "Invalid character in netname!\n");
223 static void disable_old_keys(const char *filename, const char *what) {
224 char tmpfile[PATH_MAX] = "";
226 bool disabled = false;
231 r = fopen(filename, "r");
235 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
237 w = fopen(tmpfile, "w");
239 while(fgets(buf, sizeof buf, r)) {
240 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
241 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
247 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
253 if(block || ecdsapubkey)
255 if(fputs(buf, w) < 0) {
261 if(block && !strncmp(buf, "-----END ", 9))
268 if(ferror(r) || fclose(r) < 0)
273 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
280 // We cannot atomically replace files on Windows.
281 char bakfile[PATH_MAX] = "";
282 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
283 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
284 rename(bakfile, filename);
286 if(rename(tmpfile, filename)) {
288 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
293 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
300 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
306 /* Check stdin and stdout */
308 /* Ask for a file and/or directory name. */
309 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
313 if(fgets(buf, sizeof buf, stdin) == NULL) {
314 fprintf(stderr, "Error while reading stdin: %s\n",
319 size_t len = strlen(buf);
328 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
330 if(filename[0] != '/') {
332 /* The directory is a relative path or a filename. */
333 directory = get_current_dir_name();
334 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
338 umask(0077); /* Disallow everything for group and other */
340 disable_old_keys(filename, what);
342 /* Open it first to keep the inode busy */
344 r = fopen(filename, mode);
347 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
355 Generate a public/private ECDSA keypair, and ask for a file to store
358 static bool ecdsa_keygen(bool ask) {
361 char *pubname, *privname;
363 fprintf(stderr, "Generating ECDSA keypair:\n");
365 if(!ecdsa_generate(&key)) {
366 fprintf(stderr, "Error during key generation!\n");
369 fprintf(stderr, "Done.\n");
371 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
372 f = ask_and_open(privname, "private ECDSA key", "a", ask);
379 /* Make it unreadable for others. */
380 fchmod(fileno(f), 0600);
383 ecdsa_write_pem_private_key(&key, f);
388 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
390 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
392 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
398 char *pubkey = ecdsa_get_base64_public_key(&key);
399 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
408 Generate a public/private RSA keypair, and ask for a file to store
411 static bool rsa_keygen(int bits, bool ask) {
414 char *pubname, *privname;
416 fprintf(stderr, "Generating %d bits keys:\n", bits);
418 if(!rsa_generate(&key, bits, 0x10001)) {
419 fprintf(stderr, "Error during key generation!\n");
422 fprintf(stderr, "Done.\n");
424 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
425 f = ask_and_open(privname, "private RSA key", "a", ask);
432 /* Make it unreadable for others. */
433 fchmod(fileno(f), 0600);
436 rsa_write_pem_private_key(&key, f);
441 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
443 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
445 f = ask_and_open(pubname, "public RSA key", "a", ask);
451 rsa_write_pem_public_key(&key, f);
459 Set all files and paths according to netname
461 static void make_names(void) {
464 char installdir[1024] = "";
465 long len = sizeof installdir;
469 xasprintf(&identname, "tinc.%s", netname);
471 identname = xstrdup("tinc");
474 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
475 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
478 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
480 xasprintf(&confbase, "%s", installdir);
484 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
490 confdir = xstrdup(CONFDIR);
493 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
497 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
499 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
502 xasprintf(&confbase, CONFDIR SLASH "tinc");
507 confdir = xstrdup(installdir);
510 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
511 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
514 static char buffer[4096];
515 static size_t blen = 0;
517 bool recvline(int fd, char *line, size_t len) {
518 char *newline = NULL;
520 while(!(newline = memchr(buffer, '\n', blen))) {
521 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
522 if(result == -1 && errno == EINTR)
529 if(newline - buffer >= len)
532 len = newline - buffer;
534 memcpy(line, buffer, len);
536 memmove(buffer, newline + 1, blen - len - 1);
542 static bool recvdata(int fd, char *data, size_t len) {
544 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
545 if(result == -1 && errno == EINTR)
552 memcpy(data, buffer, len);
553 memmove(buffer, buffer + len, blen - len);
559 bool sendline(int fd, char *format, ...) {
560 static char buffer[4096];
565 va_start(ap, format);
566 blen = vsnprintf(buffer, sizeof buffer, format, ap);
569 if(blen < 1 || blen >= sizeof buffer)
576 int result = send(fd, p, blen, 0);
577 if(result == -1 && errno == EINTR)
588 static void pcap(int fd, FILE *out, int snaplen) {
589 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
597 uint32_t tz_accuracy;
604 snaplen ?: sizeof data,
617 fwrite(&header, sizeof header, 1, out);
621 while(recvline(fd, line, sizeof line)) {
623 int n = sscanf(line, "%d %d %d", &code, &req, &len);
624 gettimeofday(&tv, NULL);
625 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
627 if(!recvdata(fd, data, len))
629 packet.tv_sec = tv.tv_sec;
630 packet.tv_usec = tv.tv_usec;
632 packet.origlen = len;
633 fwrite(&packet, sizeof packet, 1, out);
634 fwrite(data, len, 1, out);
639 static void logcontrol(int fd, FILE *out, int level) {
640 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
644 while(recvline(fd, line, sizeof line)) {
646 int n = sscanf(line, "%d %d %d", &code, &req, &len);
647 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
649 if(!recvdata(fd, data, len))
651 fwrite(data, len, 1, out);
658 static bool remove_service(void) {
659 SC_HANDLE manager = NULL;
660 SC_HANDLE service = NULL;
661 SERVICE_STATUS status = {0};
663 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
665 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
669 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
672 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
676 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
677 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
679 fprintf(stderr, "%s service stopped\n", identname);
681 if(!DeleteService(service)) {
682 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
686 fprintf(stderr, "%s service removed\n", identname);
692 static bool connect_tincd(bool verbose) {
697 struct timeval tv = {0, 0};
698 if(select(fd + 1, &r, NULL, NULL, &tv)) {
699 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
707 FILE *f = fopen(pidfilename, "r");
710 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
717 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
719 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
727 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
729 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
734 struct addrinfo hints = {
735 .ai_family = AF_UNSPEC,
736 .ai_socktype = SOCK_STREAM,
737 .ai_protocol = IPPROTO_TCP,
741 struct addrinfo *res = NULL;
743 if(getaddrinfo(host, port, &hints, &res) || !res) {
745 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
749 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
752 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
757 unsigned long arg = 0;
759 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
761 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
765 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
767 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
778 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
780 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
786 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
788 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
790 fprintf(stderr, "Could not fully establish control socket connection\n");
800 static int cmd_start(int argc, char *argv[]) {
801 if(connect_tincd(false)) {
803 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
805 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
810 char *slash = strrchr(program_name, '/');
813 if ((c = strrchr(program_name, '\\')) > slash)
818 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
823 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
826 for(int i = 1; i < optind; i++)
827 nargv[nargc++] = orig_argv[i];
828 for(int i = 1; i < argc; i++)
829 nargv[nargc++] = argv[i];
833 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
838 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
844 exit(execvp(c, nargv));
849 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
850 fprintf(stderr, "Error starting %s\n", c);
858 static int cmd_stop(int argc, char *argv[]) {
860 fprintf(stderr, "Too many arguments!\n");
865 if(!connect_tincd(true)) {
867 if(kill(pid, SIGTERM)) {
868 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
872 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
873 waitpid(pid, NULL, 0);
880 sendline(fd, "%d %d", CONTROL, REQ_STOP);
881 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
882 fprintf(stderr, "Could not stop tinc daemon.\n");
886 // Wait for tincd to close the connection...
890 select(fd + 1, &r, NULL, NULL, NULL);
892 if(!remove_service())
902 static int cmd_restart(int argc, char *argv[]) {
903 cmd_stop(argc, argv);
904 return cmd_start(argc, argv);
907 static int cmd_reload(int argc, char *argv[]) {
909 fprintf(stderr, "Too many arguments!\n");
913 if(!connect_tincd(true))
916 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
917 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
918 fprintf(stderr, "Could not reload configuration.\n");
926 static int cmd_dump(int argc, char *argv[]) {
927 bool only_reachable = false;
929 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
930 if(strcasecmp(argv[2], "nodes")) {
931 fprintf(stderr, "`reachable' only supported for nodes.\n");
935 only_reachable = true;
941 fprintf(stderr, "Invalid number of arguments.\n");
946 if(!connect_tincd(true))
951 if(!strcasecmp(argv[1], "nodes"))
952 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
953 else if(!strcasecmp(argv[1], "edges"))
954 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
955 else if(!strcasecmp(argv[1], "subnets"))
956 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
957 else if(!strcasecmp(argv[1], "connections"))
958 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
959 else if(!strcasecmp(argv[1], "graph")) {
960 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
961 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
963 } else if(!strcasecmp(argv[1], "digraph")) {
964 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
965 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
968 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
975 else if(do_graph == 2)
976 printf("digraph {\n");
978 while(recvline(fd, line, sizeof line)) {
979 char node1[4096], node2[4096];
980 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
982 if(do_graph && req == REQ_DUMP_NODES)
1001 int cipher, digest, maclength, compression, distance, socket, weight;
1002 short int pmtu, minmtu, maxmtu;
1003 unsigned int options, status_int;
1004 node_status_t status;
1005 long int last_state_change;
1008 case REQ_DUMP_NODES: {
1009 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_int, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change);
1011 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1015 memcpy(&status, &status_int, sizeof status);
1018 const char *color = "black";
1019 if(!strcmp(host, "MYSELF"))
1021 else if(!status.reachable)
1023 else if(strcmp(via, node))
1025 else if(!status.validkey)
1029 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1031 if(only_reachable && !status.reachable)
1033 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",
1034 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1038 case REQ_DUMP_EDGES: {
1039 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1041 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1046 float w = 1 + 65536.0 / weight;
1047 if(do_graph == 1 && strcmp(node1, node2) > 0)
1048 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1049 else if(do_graph == 2)
1050 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1052 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1056 case REQ_DUMP_SUBNETS: {
1057 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1059 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1062 printf("%s owner %s\n", strip_weight(subnet), node);
1065 case REQ_DUMP_CONNECTIONS: {
1066 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1068 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1071 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1075 fprintf(stderr, "Unable to parse dump from tincd.\n");
1080 fprintf(stderr, "Error receiving dump.\n");
1084 static int cmd_purge(int argc, char *argv[]) {
1086 fprintf(stderr, "Too many arguments!\n");
1090 if(!connect_tincd(true))
1093 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1094 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1095 fprintf(stderr, "Could not purge old information.\n");
1102 static int cmd_debug(int argc, char *argv[]) {
1104 fprintf(stderr, "Invalid number of arguments.\n");
1108 if(!connect_tincd(true))
1111 int debuglevel = atoi(argv[1]);
1114 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1115 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1116 fprintf(stderr, "Could not set debug level.\n");
1120 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1124 static int cmd_retry(int argc, char *argv[]) {
1126 fprintf(stderr, "Too many arguments!\n");
1130 if(!connect_tincd(true))
1133 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1134 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1135 fprintf(stderr, "Could not retry outgoing connections.\n");
1142 static int cmd_connect(int argc, char *argv[]) {
1144 fprintf(stderr, "Invalid number of arguments.\n");
1148 if(!check_id(argv[1])) {
1149 fprintf(stderr, "Invalid name for node.\n");
1153 if(!connect_tincd(true))
1156 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1157 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1158 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1165 static int cmd_disconnect(int argc, char *argv[]) {
1167 fprintf(stderr, "Invalid number of arguments.\n");
1171 if(!check_id(argv[1])) {
1172 fprintf(stderr, "Invalid name for node.\n");
1176 if(!connect_tincd(true))
1179 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1180 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1181 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1188 static int cmd_top(int argc, char *argv[]) {
1190 fprintf(stderr, "Too many arguments!\n");
1195 if(!connect_tincd(true))
1201 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1206 static int cmd_pcap(int argc, char *argv[]) {
1208 fprintf(stderr, "Too many arguments!\n");
1212 if(!connect_tincd(true))
1215 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1219 static int cmd_log(int argc, char *argv[]) {
1221 fprintf(stderr, "Too many arguments!\n");
1225 if(!connect_tincd(true))
1228 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1232 static int cmd_pid(int argc, char *argv[]) {
1234 fprintf(stderr, "Too many arguments!\n");
1238 if(!connect_tincd(true) && !pid)
1241 printf("%d\n", pid);
1245 static int rstrip(char *value) {
1246 int len = strlen(value);
1247 while(len && strchr("\t\r\n ", value[len - 1]))
1252 static char *get_my_name() {
1253 FILE *f = fopen(tinc_conf, "r");
1255 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1261 while(fgets(buf, sizeof buf, f)) {
1262 int len = strcspn(buf, "\t =");
1264 value += strspn(value, "\t ");
1267 value += strspn(value, "\t ");
1272 if(strcasecmp(buf, "Name"))
1276 return strdup(value);
1281 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1285 #define VAR_SERVER 1 /* Should be in tinc.conf */
1286 #define VAR_HOST 2 /* Can be in host config file */
1287 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1288 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1293 } const variables[] = {
1294 /* Server configuration */
1295 {"AddressFamily", VAR_SERVER},
1296 {"AutoConnect", VAR_SERVER},
1297 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1298 {"BindToInterface", VAR_SERVER},
1299 {"Broadcast", VAR_SERVER},
1300 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1301 {"DecrementTTL", VAR_SERVER},
1302 {"Device", VAR_SERVER},
1303 {"DeviceType", VAR_SERVER},
1304 {"DirectOnly", VAR_SERVER},
1305 {"ECDSAPrivateKeyFile", VAR_SERVER},
1306 {"ExperimentalProtocol", VAR_SERVER},
1307 {"Forwarding", VAR_SERVER},
1308 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1309 {"Hostnames", VAR_SERVER},
1310 {"IffOneQueue", VAR_SERVER},
1311 {"Interface", VAR_SERVER},
1312 {"KeyExpire", VAR_SERVER},
1313 {"LocalDiscovery", VAR_SERVER},
1314 {"MACExpire", VAR_SERVER},
1315 {"MaxOutputBufferSize", VAR_SERVER},
1316 {"MaxTimeout", VAR_SERVER},
1317 {"Mode", VAR_SERVER},
1318 {"Name", VAR_SERVER},
1319 {"PingInterval", VAR_SERVER},
1320 {"PingTimeout", VAR_SERVER},
1321 {"PriorityInheritance", VAR_SERVER},
1322 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1323 {"PrivateKeyFile", VAR_SERVER},
1324 {"ProcessPriority", VAR_SERVER},
1325 {"Proxy", VAR_SERVER},
1326 {"ReplayWindow", VAR_SERVER},
1327 {"ScriptsExtension", VAR_SERVER},
1328 {"ScriptsInterpreter", VAR_SERVER},
1329 {"StrictSubnets", VAR_SERVER},
1330 {"TunnelServer", VAR_SERVER},
1331 {"UDPRcvBuf", VAR_SERVER},
1332 {"UDPSndBuf", VAR_SERVER},
1333 {"VDEGroup", VAR_SERVER},
1334 {"VDEPort", VAR_SERVER},
1335 /* Host configuration */
1336 {"Address", VAR_HOST | VAR_MULTIPLE},
1337 {"Cipher", VAR_SERVER | VAR_HOST},
1338 {"ClampMSS", VAR_SERVER | VAR_HOST},
1339 {"Compression", VAR_SERVER | VAR_HOST},
1340 {"Digest", VAR_SERVER | VAR_HOST},
1341 {"ECDSAPublicKey", VAR_HOST},
1342 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1343 {"IndirectData", VAR_SERVER | VAR_HOST},
1344 {"MACLength", VAR_SERVER | VAR_HOST},
1345 {"PMTU", VAR_SERVER | VAR_HOST},
1346 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1348 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1349 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1350 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1351 {"TCPOnly", VAR_SERVER | VAR_HOST},
1352 {"Weight", VAR_HOST},
1356 static int cmd_config(int argc, char *argv[]) {
1358 fprintf(stderr, "Invalid number of arguments.\n");
1363 if(!strcasecmp(argv[1], "get")) {
1365 } else if(!strcasecmp(argv[1], "add")) {
1366 argv++, argc--, action = 1;
1367 } else if(!strcasecmp(argv[1], "del")) {
1368 argv++, argc--, action = -1;
1369 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1370 argv++, argc--, action = 0;
1374 fprintf(stderr, "Invalid number of arguments.\n");
1378 // Concatenate the rest of the command line
1379 strncpy(line, argv[1], sizeof line - 1);
1380 for(int i = 2; i < argc; i++) {
1381 strncat(line, " ", sizeof line - 1 - strlen(line));
1382 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1385 // Liberal parsing into node name, variable name and value.
1391 len = strcspn(line, "\t =");
1393 value += strspn(value, "\t ");
1396 value += strspn(value, "\t ");
1399 variable = strchr(line, '.');
1408 fprintf(stderr, "No variable given.\n");
1412 if(action >= 0 && !*value) {
1413 fprintf(stderr, "No value for variable given.\n");
1417 if(action < -1 && *value)
1420 /* Some simple checks. */
1423 for(int i = 0; variables[i].name; i++) {
1424 if(strcasecmp(variables[i].name, variable))
1428 variable = (char *)variables[i].name;
1430 /* Discourage use of obsolete variables. */
1432 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1434 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1436 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1441 /* Don't put server variables in host config files */
1443 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1445 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1447 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1452 /* Should this go into our own host config file? */
1454 if(!node && !(variables[i].type & VAR_SERVER)) {
1455 node = get_my_name();
1463 if(node && !check_id(node)) {
1464 fprintf(stderr, "Invalid name for node.\n");
1469 if(force || action < 0) {
1470 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1472 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1477 // Open the right configuration file.
1480 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1482 filename = tinc_conf;
1484 FILE *f = fopen(filename, "r");
1486 if(action < 0 || errno != ENOENT) {
1487 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1491 // If it doesn't exist, create it.
1492 f = fopen(filename, "a+");
1494 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1497 fprintf(stderr, "Created configuration file %s.\n", filename);
1501 char *tmpfile = NULL;
1505 xasprintf(&tmpfile, "%s.config.tmp", filename);
1506 tf = fopen(tmpfile, "w");
1508 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1514 // Copy the file, making modifications on the fly, unless we are just getting a value.
1518 bool removed = false;
1521 while(fgets(buf1, sizeof buf1, f)) {
1522 buf1[sizeof buf1 - 1] = 0;
1523 strncpy(buf2, buf1, sizeof buf2);
1525 // Parse line in a simple way
1529 len = strcspn(buf2, "\t =");
1530 bvalue = buf2 + len;
1531 bvalue += strspn(bvalue, "\t ");
1532 if(*bvalue == '=') {
1534 bvalue += strspn(bvalue, "\t ");
1540 if(!strcasecmp(buf2, variable)) {
1544 printf("%s\n", bvalue);
1546 } else if(action == -1) {
1547 if(!*value || !strcasecmp(bvalue, value)) {
1552 } else if(action == 0) {
1553 // Already set? Delete the rest...
1556 // Otherwise, replace.
1557 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1558 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1567 // Copy original line...
1568 if(fputs(buf1, tf) < 0) {
1569 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1573 // Add newline if it is missing...
1574 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1575 if(fputc('\n', tf) < 0) {
1576 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1583 // Make sure we read everything...
1584 if(ferror(f) || !feof(f)) {
1585 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1590 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1594 // Add new variable if necessary.
1595 if(action > 0 || (action == 0 && !set)) {
1596 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1597 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1604 fprintf(stderr, "No matching configuration variables found.\n");
1608 // Make sure we wrote everything...
1610 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1614 // Could we find what we had to remove?
1615 if(action < 0 && !removed) {
1617 fprintf(stderr, "No configuration variables deleted.\n");
1621 // Replace the configuration file with the new one
1623 if(remove(filename)) {
1624 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1628 if(rename(tmpfile, filename)) {
1629 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1633 // Silently try notifying a running tincd of changes.
1634 if(connect_tincd(false))
1635 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1640 bool check_id(const char *name) {
1644 for(int i = 0; i < strlen(name); i++) {
1645 if(!isalnum(name[i]) && name[i] != '_')
1652 static int cmd_init(int argc, char *argv[]) {
1653 if(!access(tinc_conf, F_OK)) {
1654 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1659 fprintf(stderr, "Too many arguments!\n");
1661 } else if(argc < 2) {
1664 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1666 if(!fgets(buf, sizeof buf, stdin)) {
1667 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1670 int len = rstrip(buf);
1672 fprintf(stderr, "No name given!\n");
1677 fprintf(stderr, "No Name given!\n");
1681 name = strdup(argv[1]);
1683 fprintf(stderr, "No Name given!\n");
1688 if(!check_id(name)) {
1689 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1693 if(mkdir(confdir, 0755) && errno != EEXIST) {
1694 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1698 if(mkdir(confbase, 0755) && errno != EEXIST) {
1699 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1703 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1704 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1708 FILE *f = fopen(tinc_conf, "w");
1710 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1714 fprintf(f, "Name = %s\n", name);
1717 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1722 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1723 if(access(filename, F_OK)) {
1724 FILE *f = fopen(filename, "w");
1726 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1729 fchmod(fileno(f), 0755);
1730 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");
1739 static int cmd_generate_keys(int argc, char *argv[]) {
1741 fprintf(stderr, "Too many arguments!\n");
1745 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1748 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1750 fprintf(stderr, "Too many arguments!\n");
1754 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1757 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1759 fprintf(stderr, "Too many arguments!\n");
1763 return !ecdsa_keygen(true);
1766 static int cmd_help(int argc, char *argv[]) {
1771 static int cmd_version(int argc, char *argv[]) {
1773 fprintf(stderr, "Too many arguments!\n");
1781 static int cmd_info(int argc, char *argv[]) {
1783 fprintf(stderr, "Invalid number of arguments.\n");
1787 if(!connect_tincd(true))
1790 return info(fd, argv[1]);
1793 static const char *conffiles[] = {
1804 static int cmd_edit(int argc, char *argv[]) {
1806 fprintf(stderr, "Invalid number of arguments.\n");
1810 char *filename = NULL;
1812 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1813 for(int i = 0; conffiles[i]; i++) {
1814 if(!strcmp(argv[1], conffiles[i])) {
1815 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1824 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1825 char *dash = strchr(argv[1], '-');
1828 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1829 fprintf(stderr, "Invalid configuration filename.\n");
1837 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1839 xasprintf(&command, "edit \"%s\"", filename);
1841 int result = system(command);
1845 // Silently try notifying a running tincd of changes.
1846 if(connect_tincd(false))
1847 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1852 static int export(const char *name, FILE *out) {
1854 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1855 FILE *in = fopen(filename, "r");
1857 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1861 fprintf(out, "Name = %s\n", name);
1863 while(fgets(buf, sizeof buf, in)) {
1864 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1869 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1878 static int cmd_export(int argc, char *argv[]) {
1880 fprintf(stderr, "Too many arguments!\n");
1884 char *name = get_my_name();
1888 int result = export(name, stdout);
1894 static int cmd_export_all(int argc, char *argv[]) {
1896 fprintf(stderr, "Too many arguments!\n");
1900 DIR *dir = opendir(hosts_dir);
1902 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1910 while((ent = readdir(dir))) {
1911 if(!check_id(ent->d_name))
1917 printf("#---------------------------------------------------------------#\n");
1919 result |= export(ent->d_name, stdout);
1928 static int cmd_import(int argc, char *argv[]) {
1930 fprintf(stderr, "Too many arguments!\n");
1939 char *filename = NULL;
1941 bool firstline = true;
1943 while(fgets(buf, sizeof buf, in)) {
1944 if(sscanf(buf, "Name = %s", name) == 1) {
1947 if(!check_id(name)) {
1948 fprintf(stderr, "Invalid Name in input!\n");
1956 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1958 if(!force && !access(filename, F_OK)) {
1959 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1964 out = fopen(filename, "w");
1966 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1972 } else if(firstline) {
1973 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1978 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1982 if(fputs(buf, out) < 0) {
1983 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1993 fprintf(stderr, "Imported %d host configuration files.\n", count);
1996 fprintf(stderr, "No host configuration files imported.\n");
2001 static int cmd_exchange(int argc, char *argv[]) {
2002 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2005 static int cmd_exchange_all(int argc, char *argv[]) {
2006 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2009 static const struct {
2010 const char *command;
2011 int (*function)(int argc, char *argv[]);
2013 {"start", cmd_start},
2015 {"restart", cmd_restart},
2016 {"reload", cmd_reload},
2018 {"purge", cmd_purge},
2019 {"debug", cmd_debug},
2020 {"retry", cmd_retry},
2021 {"connect", cmd_connect},
2022 {"disconnect", cmd_disconnect},
2027 {"config", cmd_config},
2029 {"generate-keys", cmd_generate_keys},
2030 {"generate-rsa-keys", cmd_generate_rsa_keys},
2031 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2033 {"version", cmd_version},
2036 {"export", cmd_export},
2037 {"export-all", cmd_export_all},
2038 {"import", cmd_import},
2039 {"exchange", cmd_exchange},
2040 {"exchange-all", cmd_exchange_all},
2044 #ifdef HAVE_READLINE
2045 static char *complete_command(const char *text, int state) {
2053 while(commands[i].command) {
2054 if(!strncasecmp(commands[i].command, text, strlen(text)))
2055 return xstrdup(commands[i].command);
2062 static char *complete_dump(const char *text, int state) {
2063 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2072 if(!strncasecmp(matches[i], text, strlen(text)))
2073 return xstrdup(matches[i]);
2080 static char *complete_config(const char *text, int state) {
2081 const char *sub[] = {"get", "set", "add", "del"};
2085 if(!strchr(rl_line_buffer + 7, ' '))
2089 for(int i = 0; i < 4; i++) {
2090 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2102 while(i < 0 || variables[i].name) {
2103 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2104 return xstrdup(sub[i + 4]);
2106 char *dot = strchr(text, '.');
2108 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2110 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2114 if(!strncasecmp(variables[i].name, text, strlen(text)))
2115 return xstrdup(variables[i].name);
2124 static char *complete_info(const char *text, int state) {
2128 if(!connect_tincd(false))
2130 // Check the list of nodes
2131 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2132 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2135 while(recvline(fd, line, sizeof line)) {
2137 int n = sscanf(line, "%d %d %s", &code, &req, item);
2147 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2151 if(!strncmp(item, text, strlen(text)))
2152 return xstrdup(strip_weight(item));
2158 static char *complete_nothing(const char *text, int state) {
2162 static char **completion (const char *text, int start, int end) {
2163 char **matches = NULL;
2166 matches = rl_completion_matches(text, complete_command);
2167 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2168 matches = rl_completion_matches(text, complete_dump);
2169 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2170 matches = rl_completion_matches(text, complete_config);
2171 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2172 matches = rl_completion_matches(text, complete_info);
2178 static int cmd_shell(int argc, char *argv[]) {
2180 xasprintf(&prompt, "%s> ", identname);
2184 int maxargs = argc + 16;
2185 char **nargv = xmalloc(maxargs * sizeof *nargv);
2187 for(int i = 0; i < argc; i++)
2190 #ifdef HAVE_READLINE
2191 rl_readline_name = "tinc";
2192 rl_completion_entry_function = complete_nothing;
2193 rl_attempted_completion_function = completion;
2194 rl_filename_completion_desired = 0;
2199 #ifdef HAVE_READLINE
2203 rl_basic_word_break_characters = "\t\n ";
2204 line = readline(prompt);
2206 copy = xstrdup(line);
2208 line = fgets(buf, sizeof buf, stdin);
2212 fputs(prompt, stdout);
2214 line = fgets(buf, sizeof buf, stdin);
2220 /* Ignore comments */
2228 char *p = line + strspn(line, " \t\n");
2229 char *next = strtok(p, " \t\n");
2232 if(nargc >= maxargs) {
2233 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2236 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2241 next = strtok(NULL, " \t\n");
2247 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2252 for(int i = 0; commands[i].command; i++) {
2253 if(!strcasecmp(nargv[argc], commands[i].command)) {
2254 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2260 #ifdef HAVE_READLINE
2266 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2279 int main(int argc, char *argv[]) {
2280 program_name = argv[0];
2284 if(!parse_options(argc, argv))
2299 tty = isatty(0) && isatty(1);
2302 return cmd_shell(argc, argv);
2304 for(int i = 0; commands[i].command; i++) {
2305 if(!strcasecmp(argv[optind], commands[i].command))
2306 return commands[i].function(argc - optind, argv + optind);
2309 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);