2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2013 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"
41 #define mkdir(a, b) mkdir(a)
44 static char **orig_argv;
47 /* If nonzero, display usage information and exit. */
48 static bool show_help = false;
50 /* If nonzero, print the version on standard output and exit. */
51 static bool show_version = false;
53 static char *name = NULL;
54 static char controlcookie[1025];
55 static char *tinc_conf = NULL;
56 static char *hosts_dir = NULL;
59 // Horrible global variables...
62 static char line[4096];
66 static bool force = false;
67 static bool tty = true;
70 static struct WSAData wsa_state;
73 static struct option const long_options[] = {
74 {"config", required_argument, NULL, 'c'},
75 {"debug", optional_argument, NULL, 0},
76 {"no-detach", no_argument, NULL, 0},
77 {"mlock", no_argument, NULL, 0},
78 {"net", required_argument, NULL, 'n'},
79 {"help", no_argument, NULL, 1},
80 {"version", no_argument, NULL, 2},
81 {"pidfile", required_argument, NULL, 5},
82 {"logfile", required_argument, NULL, 0},
83 {"bypass-security", no_argument, NULL, 0},
84 {"chroot", no_argument, NULL, 0},
85 {"user", required_argument, NULL, 0},
86 {"option", required_argument, NULL, 0},
87 {"force", no_argument, NULL, 6},
91 static void version(void) {
92 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
93 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
94 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
95 "See the AUTHORS file for a complete list.\n\n"
96 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
97 "and you are welcome to redistribute it under certain conditions;\n"
98 "see the file COPYING for details.\n");
101 static void usage(bool status) {
103 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
105 printf("Usage: %s [options] command\n\n", program_name);
106 printf("Valid options are:\n"
107 " -c, --config=DIR Read configuration options from DIR.\n"
108 " -n, --net=NETNAME Connect to net NETNAME.\n"
109 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
110 " --help Display this help and exit.\n"
111 " --version Output version information and exit.\n"
113 "Valid commands are:\n"
114 " init [name] Create initial configuration files.\n"
115 " get VARIABLE Print current value of VARIABLE\n"
116 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
117 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
118 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
119 " start [tincd options] Start tincd.\n"
120 " stop Stop tincd.\n"
121 " restart Restart tincd.\n"
122 " reload Partially reload configuration of running tincd.\n"
123 " pid Show PID of currently running tincd.\n"
124 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
125 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
126 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
127 " dump Dump a list of one of the following things:\n"
128 " [reachable] nodes - all known nodes in the VPN\n"
129 " edges - all known connections in the VPN\n"
130 " subnets - all known subnets in the VPN\n"
131 " connections - all meta connections with ourself\n"
132 " [di]graph - graph of the VPN in dotty format\n"
133 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
134 " purge Purge unreachable nodes\n"
135 " debug N Set debug level\n"
136 " retry Retry all outgoing connections\n"
137 " disconnect NODE Close meta connection with NODE\n"
139 " top Show real-time statistics\n"
141 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
142 " log [level] Dump log output [up to the specified level]\n"
143 " export Export host configuration of local node to standard output\n"
144 " export-all Export all host configuration files to standard output\n"
145 " import [--force] Import host configuration file(s) from standard input\n"
146 " exchange [--force] Same as export followed by import\n"
147 " exchange-all [--force] Same as export-all followed by import\n"
149 printf("Report bugs to tinc@tinc-vpn.org.\n");
153 static bool parse_options(int argc, char **argv) {
155 int option_index = 0;
157 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
159 case 0: /* long option */
162 case 'c': /* config file */
163 confbase = xstrdup(optarg);
166 case 'n': /* net name given */
167 netname = xstrdup(optarg);
170 case 1: /* show help */
174 case 2: /* show version */
178 case 5: /* open control socket here */
179 pidfilename = xstrdup(optarg);
186 case '?': /* wrong options */
195 if(!netname && (netname = getenv("NETNAME")))
196 netname = xstrdup(netname);
198 /* netname "." is special: a "top-level name" */
200 if(netname && (!*netname || !strcmp(netname, "."))) {
205 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
206 fprintf(stderr, "Invalid character in netname!\n");
213 static void disable_old_keys(const char *filename, const char *what) {
214 char tmpfile[PATH_MAX] = "";
216 bool disabled = false;
221 r = fopen(filename, "r");
225 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
227 w = fopen(tmpfile, "w");
229 while(fgets(buf, sizeof buf, r)) {
230 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
231 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
237 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
243 if(block || ecdsapubkey)
245 if(fputs(buf, w) < 0) {
251 if(block && !strncmp(buf, "-----END ", 9))
258 if(ferror(r) || fclose(r) < 0)
263 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
270 // We cannot atomically replace files on Windows.
271 char bakfile[PATH_MAX] = "";
272 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
273 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
274 rename(bakfile, filename);
276 if(rename(tmpfile, filename)) {
278 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
283 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
290 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
296 /* Check stdin and stdout */
298 /* Ask for a file and/or directory name. */
299 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
303 if(fgets(buf, sizeof buf, stdin) == NULL) {
304 fprintf(stderr, "Error while reading stdin: %s\n",
309 size_t len = strlen(buf);
318 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
320 if(filename[0] != '/') {
322 /* The directory is a relative path or a filename. */
323 directory = get_current_dir_name();
324 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
328 umask(0077); /* Disallow everything for group and other */
330 disable_old_keys(filename, what);
332 /* Open it first to keep the inode busy */
334 r = fopen(filename, mode);
337 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
345 Generate a public/private ECDSA keypair, and ask for a file to store
348 static bool ecdsa_keygen(bool ask) {
351 char *pubname, *privname;
353 fprintf(stderr, "Generating ECDSA keypair:\n");
355 if(!ecdsa_generate(&key)) {
356 fprintf(stderr, "Error during key generation!\n");
359 fprintf(stderr, "Done.\n");
361 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
362 f = ask_and_open(privname, "private ECDSA key", "a", ask);
369 /* Make it unreadable for others. */
370 fchmod(fileno(f), 0600);
373 ecdsa_write_pem_private_key(&key, f);
378 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
380 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
382 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
388 char *pubkey = ecdsa_get_base64_public_key(&key);
389 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
398 Generate a public/private RSA keypair, and ask for a file to store
401 static bool rsa_keygen(int bits, bool ask) {
404 char *pubname, *privname;
406 fprintf(stderr, "Generating %d bits keys:\n", bits);
408 if(!rsa_generate(&key, bits, 0x10001)) {
409 fprintf(stderr, "Error during key generation!\n");
412 fprintf(stderr, "Done.\n");
414 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
415 f = ask_and_open(privname, "private RSA key", "a", ask);
422 /* Make it unreadable for others. */
423 fchmod(fileno(f), 0600);
426 rsa_write_pem_private_key(&key, f);
431 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
433 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
435 f = ask_and_open(pubname, "public RSA key", "a", ask);
441 rsa_write_pem_public_key(&key, f);
448 static char buffer[4096];
449 static size_t blen = 0;
451 bool recvline(int fd, char *line, size_t len) {
452 char *newline = NULL;
454 while(!(newline = memchr(buffer, '\n', blen))) {
455 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
456 if(result == -1 && errno == EINTR)
463 if(newline - buffer >= len)
466 len = newline - buffer;
468 memcpy(line, buffer, len);
470 memmove(buffer, newline + 1, blen - len - 1);
476 static bool recvdata(int fd, char *data, size_t len) {
478 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
479 if(result == -1 && errno == EINTR)
486 memcpy(data, buffer, len);
487 memmove(buffer, buffer + len, blen - len);
493 bool sendline(int fd, char *format, ...) {
494 static char buffer[4096];
499 va_start(ap, format);
500 blen = vsnprintf(buffer, sizeof buffer, format, ap);
503 if(blen < 1 || blen >= sizeof buffer)
510 int result = send(fd, p, blen, 0);
511 if(result == -1 && errno == EINTR)
522 static void pcap(int fd, FILE *out, int snaplen) {
523 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
531 uint32_t tz_accuracy;
538 snaplen ?: sizeof data,
551 fwrite(&header, sizeof header, 1, out);
555 while(recvline(fd, line, sizeof line)) {
557 int n = sscanf(line, "%d %d %d", &code, &req, &len);
558 gettimeofday(&tv, NULL);
559 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
561 if(!recvdata(fd, data, len))
563 packet.tv_sec = tv.tv_sec;
564 packet.tv_usec = tv.tv_usec;
566 packet.origlen = len;
567 fwrite(&packet, sizeof packet, 1, out);
568 fwrite(data, len, 1, out);
573 static void logcontrol(int fd, FILE *out, int level) {
574 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
578 while(recvline(fd, line, sizeof line)) {
580 int n = sscanf(line, "%d %d %d", &code, &req, &len);
581 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
583 if(!recvdata(fd, data, len))
585 fwrite(data, len, 1, out);
592 static bool remove_service(void) {
593 SC_HANDLE manager = NULL;
594 SC_HANDLE service = NULL;
595 SERVICE_STATUS status = {0};
597 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
599 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
603 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
606 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
610 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
611 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
613 fprintf(stderr, "%s service stopped\n", identname);
615 if(!DeleteService(service)) {
616 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
620 fprintf(stderr, "%s service removed\n", identname);
626 static bool connect_tincd(bool verbose) {
631 struct timeval tv = {0, 0};
632 if(select(fd + 1, &r, NULL, NULL, &tv)) {
633 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
641 FILE *f = fopen(pidfilename, "r");
644 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
651 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
653 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
661 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
663 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
669 struct sockaddr_un sa;
670 sa.sun_family = AF_UNIX;
671 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
673 fd = socket(AF_UNIX, SOCK_STREAM, 0);
676 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
680 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
682 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
688 struct addrinfo hints = {
689 .ai_family = AF_UNSPEC,
690 .ai_socktype = SOCK_STREAM,
691 .ai_protocol = IPPROTO_TCP,
695 struct addrinfo *res = NULL;
697 if(getaddrinfo(host, port, &hints, &res) || !res) {
699 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
703 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
706 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
711 unsigned long arg = 0;
713 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
715 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
719 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
721 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
733 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
735 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
741 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
743 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
745 fprintf(stderr, "Could not fully establish control socket connection\n");
755 static int cmd_start(int argc, char *argv[]) {
756 if(connect_tincd(false)) {
758 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
760 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
765 char *slash = strrchr(program_name, '/');
768 if ((c = strrchr(program_name, '\\')) > slash)
773 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
778 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
781 for(int i = 1; i < optind; i++)
782 nargv[nargc++] = orig_argv[i];
783 for(int i = 1; i < argc; i++)
784 nargv[nargc++] = argv[i];
788 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
793 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
799 exit(execvp(c, nargv));
804 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
805 fprintf(stderr, "Error starting %s\n", c);
813 static int cmd_stop(int argc, char *argv[]) {
815 fprintf(stderr, "Too many arguments!\n");
820 if(!connect_tincd(true)) {
822 if(kill(pid, SIGTERM)) {
823 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
827 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
828 waitpid(pid, NULL, 0);
835 sendline(fd, "%d %d", CONTROL, REQ_STOP);
837 while(recvline(fd, line, sizeof line)) {
838 // Wait for tincd to close the connection...
841 if(!remove_service())
851 static int cmd_restart(int argc, char *argv[]) {
852 cmd_stop(argc, argv);
853 return cmd_start(argc, argv);
856 static int cmd_reload(int argc, char *argv[]) {
858 fprintf(stderr, "Too many arguments!\n");
862 if(!connect_tincd(true))
865 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
866 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
867 fprintf(stderr, "Could not reload configuration.\n");
875 static int cmd_dump(int argc, char *argv[]) {
876 bool only_reachable = false;
878 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
879 if(strcasecmp(argv[2], "nodes")) {
880 fprintf(stderr, "`reachable' only supported for nodes.\n");
884 only_reachable = true;
890 fprintf(stderr, "Invalid number of arguments.\n");
895 if(!connect_tincd(true))
900 if(!strcasecmp(argv[1], "nodes"))
901 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
902 else if(!strcasecmp(argv[1], "edges"))
903 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
904 else if(!strcasecmp(argv[1], "subnets"))
905 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
906 else if(!strcasecmp(argv[1], "connections"))
907 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
908 else if(!strcasecmp(argv[1], "graph")) {
909 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
910 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
912 } else if(!strcasecmp(argv[1], "digraph")) {
913 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
914 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
917 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
924 else if(do_graph == 2)
925 printf("digraph {\n");
927 while(recvline(fd, line, sizeof line)) {
928 char node1[4096], node2[4096];
929 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
931 if(do_graph && req == REQ_DUMP_NODES)
950 int cipher, digest, maclength, compression, distance, socket, weight;
951 short int pmtu, minmtu, maxmtu;
952 unsigned int options, status_int;
953 node_status_t status;
954 long int last_state_change;
957 case REQ_DUMP_NODES: {
958 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);
960 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
964 memcpy(&status, &status_int, sizeof status);
967 const char *color = "black";
968 if(!strcmp(host, "MYSELF"))
970 else if(!status.reachable)
972 else if(strcmp(via, node))
974 else if(!status.validkey)
978 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
980 if(only_reachable && !status.reachable)
982 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",
983 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
987 case REQ_DUMP_EDGES: {
988 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
990 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
995 float w = 1 + 65536.0 / weight;
996 if(do_graph == 1 && strcmp(node1, node2) > 0)
997 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
998 else if(do_graph == 2)
999 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1001 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1005 case REQ_DUMP_SUBNETS: {
1006 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1008 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1011 printf("%s owner %s\n", strip_weight(subnet), node);
1014 case REQ_DUMP_CONNECTIONS: {
1015 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1017 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1020 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1024 fprintf(stderr, "Unable to parse dump from tincd.\n");
1029 fprintf(stderr, "Error receiving dump.\n");
1033 static int cmd_purge(int argc, char *argv[]) {
1035 fprintf(stderr, "Too many arguments!\n");
1039 if(!connect_tincd(true))
1042 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1043 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1044 fprintf(stderr, "Could not purge old information.\n");
1051 static int cmd_debug(int argc, char *argv[]) {
1053 fprintf(stderr, "Invalid number of arguments.\n");
1057 if(!connect_tincd(true))
1060 int debuglevel = atoi(argv[1]);
1063 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1064 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1065 fprintf(stderr, "Could not set debug level.\n");
1069 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1073 static int cmd_retry(int argc, char *argv[]) {
1075 fprintf(stderr, "Too many arguments!\n");
1079 if(!connect_tincd(true))
1082 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1083 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1084 fprintf(stderr, "Could not retry outgoing connections.\n");
1091 static int cmd_connect(int argc, char *argv[]) {
1093 fprintf(stderr, "Invalid number of arguments.\n");
1097 if(!check_id(argv[1])) {
1098 fprintf(stderr, "Invalid name for node.\n");
1102 if(!connect_tincd(true))
1105 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1106 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1107 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1114 static int cmd_disconnect(int argc, char *argv[]) {
1116 fprintf(stderr, "Invalid number of arguments.\n");
1120 if(!check_id(argv[1])) {
1121 fprintf(stderr, "Invalid name for node.\n");
1125 if(!connect_tincd(true))
1128 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1129 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1130 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1137 static int cmd_top(int argc, char *argv[]) {
1139 fprintf(stderr, "Too many arguments!\n");
1144 if(!connect_tincd(true))
1150 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1155 static int cmd_pcap(int argc, char *argv[]) {
1157 fprintf(stderr, "Too many arguments!\n");
1161 if(!connect_tincd(true))
1164 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1168 static int cmd_log(int argc, char *argv[]) {
1170 fprintf(stderr, "Too many arguments!\n");
1174 if(!connect_tincd(true))
1177 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1181 static int cmd_pid(int argc, char *argv[]) {
1183 fprintf(stderr, "Too many arguments!\n");
1187 if(!connect_tincd(true) && !pid)
1190 printf("%d\n", pid);
1194 static int rstrip(char *value) {
1195 int len = strlen(value);
1196 while(len && strchr("\t\r\n ", value[len - 1]))
1201 static char *get_my_name(bool verbose) {
1202 FILE *f = fopen(tinc_conf, "r");
1205 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1211 while(fgets(buf, sizeof buf, f)) {
1212 int len = strcspn(buf, "\t =");
1214 value += strspn(value, "\t ");
1217 value += strspn(value, "\t ");
1222 if(strcasecmp(buf, "Name"))
1226 return strdup(value);
1232 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1236 #define VAR_SERVER 1 /* Should be in tinc.conf */
1237 #define VAR_HOST 2 /* Can be in host config file */
1238 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1239 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1244 } const variables[] = {
1245 /* Server configuration */
1246 {"AddressFamily", VAR_SERVER},
1247 {"AutoConnect", VAR_SERVER},
1248 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1249 {"BindToInterface", VAR_SERVER},
1250 {"Broadcast", VAR_SERVER},
1251 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1252 {"DecrementTTL", VAR_SERVER},
1253 {"Device", VAR_SERVER},
1254 {"DeviceType", VAR_SERVER},
1255 {"DirectOnly", VAR_SERVER},
1256 {"ECDSAPrivateKeyFile", VAR_SERVER},
1257 {"ExperimentalProtocol", VAR_SERVER},
1258 {"Forwarding", VAR_SERVER},
1259 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1260 {"Hostnames", VAR_SERVER},
1261 {"IffOneQueue", VAR_SERVER},
1262 {"Interface", VAR_SERVER},
1263 {"KeyExpire", VAR_SERVER},
1264 {"LocalDiscovery", VAR_SERVER},
1265 {"MACExpire", VAR_SERVER},
1266 {"MaxOutputBufferSize", VAR_SERVER},
1267 {"MaxTimeout", VAR_SERVER},
1268 {"Mode", VAR_SERVER},
1269 {"Name", VAR_SERVER},
1270 {"PingInterval", VAR_SERVER},
1271 {"PingTimeout", VAR_SERVER},
1272 {"PriorityInheritance", VAR_SERVER},
1273 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1274 {"PrivateKeyFile", VAR_SERVER},
1275 {"ProcessPriority", VAR_SERVER},
1276 {"Proxy", VAR_SERVER},
1277 {"ReplayWindow", VAR_SERVER},
1278 {"ScriptsExtension", VAR_SERVER},
1279 {"ScriptsInterpreter", VAR_SERVER},
1280 {"StrictSubnets", VAR_SERVER},
1281 {"TunnelServer", VAR_SERVER},
1282 {"UDPRcvBuf", VAR_SERVER},
1283 {"UDPSndBuf", VAR_SERVER},
1284 {"VDEGroup", VAR_SERVER},
1285 {"VDEPort", VAR_SERVER},
1286 /* Host configuration */
1287 {"Address", VAR_HOST | VAR_MULTIPLE},
1288 {"Cipher", VAR_SERVER | VAR_HOST},
1289 {"ClampMSS", VAR_SERVER | VAR_HOST},
1290 {"Compression", VAR_SERVER | VAR_HOST},
1291 {"Digest", VAR_SERVER | VAR_HOST},
1292 {"ECDSAPublicKey", VAR_HOST},
1293 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1294 {"IndirectData", VAR_SERVER | VAR_HOST},
1295 {"MACLength", VAR_SERVER | VAR_HOST},
1296 {"PMTU", VAR_SERVER | VAR_HOST},
1297 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1299 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1300 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1301 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1302 {"TCPOnly", VAR_SERVER | VAR_HOST},
1303 {"Weight", VAR_HOST},
1307 static int cmd_config(int argc, char *argv[]) {
1309 fprintf(stderr, "Invalid number of arguments.\n");
1313 if(strcasecmp(argv[0], "config"))
1317 if(!strcasecmp(argv[1], "get")) {
1319 } else if(!strcasecmp(argv[1], "add")) {
1320 argv++, argc--, action = 1;
1321 } else if(!strcasecmp(argv[1], "del")) {
1322 argv++, argc--, action = -1;
1323 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1324 argv++, argc--, action = 0;
1328 fprintf(stderr, "Invalid number of arguments.\n");
1332 // Concatenate the rest of the command line
1333 strncpy(line, argv[1], sizeof line - 1);
1334 for(int i = 2; i < argc; i++) {
1335 strncat(line, " ", sizeof line - 1 - strlen(line));
1336 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1339 // Liberal parsing into node name, variable name and value.
1345 len = strcspn(line, "\t =");
1347 value += strspn(value, "\t ");
1350 value += strspn(value, "\t ");
1353 variable = strchr(line, '.');
1362 fprintf(stderr, "No variable given.\n");
1366 if(action >= 0 && !*value) {
1367 fprintf(stderr, "No value for variable given.\n");
1371 if(action < -1 && *value)
1374 /* Some simple checks. */
1377 for(int i = 0; variables[i].name; i++) {
1378 if(strcasecmp(variables[i].name, variable))
1382 variable = (char *)variables[i].name;
1384 /* Discourage use of obsolete variables. */
1386 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1388 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1390 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1395 /* Don't put server variables in host config files */
1397 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1399 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1401 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1406 /* Should this go into our own host config file? */
1408 if(!node && !(variables[i].type & VAR_SERVER)) {
1409 node = get_my_name(true);
1417 if(node && !check_id(node)) {
1418 fprintf(stderr, "Invalid name for node.\n");
1423 if(force || action < 0) {
1424 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1426 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1431 // Open the right configuration file.
1434 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1436 filename = tinc_conf;
1438 FILE *f = fopen(filename, "r");
1440 if(action < 0 || errno != ENOENT) {
1441 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1445 // If it doesn't exist, create it.
1446 f = fopen(filename, "a+");
1448 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1451 fprintf(stderr, "Created configuration file %s.\n", filename);
1455 char *tmpfile = NULL;
1459 xasprintf(&tmpfile, "%s.config.tmp", filename);
1460 tf = fopen(tmpfile, "w");
1462 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1468 // Copy the file, making modifications on the fly, unless we are just getting a value.
1472 bool removed = false;
1475 while(fgets(buf1, sizeof buf1, f)) {
1476 buf1[sizeof buf1 - 1] = 0;
1477 strncpy(buf2, buf1, sizeof buf2);
1479 // Parse line in a simple way
1483 len = strcspn(buf2, "\t =");
1484 bvalue = buf2 + len;
1485 bvalue += strspn(bvalue, "\t ");
1486 if(*bvalue == '=') {
1488 bvalue += strspn(bvalue, "\t ");
1494 if(!strcasecmp(buf2, variable)) {
1498 printf("%s\n", bvalue);
1500 } else if(action == -1) {
1501 if(!*value || !strcasecmp(bvalue, value)) {
1506 } else if(action == 0) {
1507 // Already set? Delete the rest...
1510 // Otherwise, replace.
1511 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1512 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1521 // Copy original line...
1522 if(fputs(buf1, tf) < 0) {
1523 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1527 // Add newline if it is missing...
1528 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1529 if(fputc('\n', tf) < 0) {
1530 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1537 // Make sure we read everything...
1538 if(ferror(f) || !feof(f)) {
1539 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1544 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1548 // Add new variable if necessary.
1549 if(action > 0 || (action == 0 && !set)) {
1550 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1551 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1558 fprintf(stderr, "No matching configuration variables found.\n");
1562 // Make sure we wrote everything...
1564 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1568 // Could we find what we had to remove?
1569 if(action < 0 && !removed) {
1571 fprintf(stderr, "No configuration variables deleted.\n");
1575 // Replace the configuration file with the new one
1577 if(remove(filename)) {
1578 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1582 if(rename(tmpfile, filename)) {
1583 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1587 // Silently try notifying a running tincd of changes.
1588 if(connect_tincd(false))
1589 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1594 bool check_id(const char *name) {
1598 for(int i = 0; i < strlen(name); i++) {
1599 if(!isalnum(name[i]) && name[i] != '_')
1606 static int cmd_init(int argc, char *argv[]) {
1607 if(!access(tinc_conf, F_OK)) {
1608 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1613 fprintf(stderr, "Too many arguments!\n");
1615 } else if(argc < 2) {
1618 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1620 if(!fgets(buf, sizeof buf, stdin)) {
1621 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1624 int len = rstrip(buf);
1626 fprintf(stderr, "No name given!\n");
1631 fprintf(stderr, "No Name given!\n");
1635 name = strdup(argv[1]);
1637 fprintf(stderr, "No Name given!\n");
1642 if(!check_id(name)) {
1643 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1647 if(mkdir(confdir, 0755) && errno != EEXIST) {
1648 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1652 if(mkdir(confbase, 0755) && errno != EEXIST) {
1653 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1657 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1658 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1662 FILE *f = fopen(tinc_conf, "w");
1664 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1668 fprintf(f, "Name = %s\n", name);
1671 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1676 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1677 if(access(filename, F_OK)) {
1678 FILE *f = fopen(filename, "w");
1680 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1683 fchmod(fileno(f), 0755);
1684 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");
1693 static int cmd_generate_keys(int argc, char *argv[]) {
1695 fprintf(stderr, "Too many arguments!\n");
1700 name = get_my_name(false);
1702 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1705 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1707 fprintf(stderr, "Too many arguments!\n");
1712 name = get_my_name(false);
1714 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1717 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1719 fprintf(stderr, "Too many arguments!\n");
1724 name = get_my_name(false);
1726 return !ecdsa_keygen(true);
1729 static int cmd_help(int argc, char *argv[]) {
1734 static int cmd_version(int argc, char *argv[]) {
1736 fprintf(stderr, "Too many arguments!\n");
1744 static int cmd_info(int argc, char *argv[]) {
1746 fprintf(stderr, "Invalid number of arguments.\n");
1750 if(!connect_tincd(true))
1753 return info(fd, argv[1]);
1756 static const char *conffiles[] = {
1767 static int cmd_edit(int argc, char *argv[]) {
1769 fprintf(stderr, "Invalid number of arguments.\n");
1773 char *filename = NULL;
1775 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1776 for(int i = 0; conffiles[i]; i++) {
1777 if(!strcmp(argv[1], conffiles[i])) {
1778 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1787 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1788 char *dash = strchr(argv[1], '-');
1791 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1792 fprintf(stderr, "Invalid configuration filename.\n");
1800 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1802 xasprintf(&command, "edit \"%s\"", filename);
1804 int result = system(command);
1808 // Silently try notifying a running tincd of changes.
1809 if(connect_tincd(false))
1810 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1815 static int export(const char *name, FILE *out) {
1817 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1818 FILE *in = fopen(filename, "r");
1820 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1824 fprintf(out, "Name = %s\n", name);
1826 while(fgets(buf, sizeof buf, in)) {
1827 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1832 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1841 static int cmd_export(int argc, char *argv[]) {
1843 fprintf(stderr, "Too many arguments!\n");
1847 char *name = get_my_name(true);
1851 int result = export(name, stdout);
1859 static int cmd_export_all(int argc, char *argv[]) {
1861 fprintf(stderr, "Too many arguments!\n");
1865 DIR *dir = opendir(hosts_dir);
1867 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1875 while((ent = readdir(dir))) {
1876 if(!check_id(ent->d_name))
1882 printf("#---------------------------------------------------------------#\n");
1884 result |= export(ent->d_name, stdout);
1893 static int cmd_import(int argc, char *argv[]) {
1895 fprintf(stderr, "Too many arguments!\n");
1904 char *filename = NULL;
1906 bool firstline = true;
1908 while(fgets(buf, sizeof buf, in)) {
1909 if(sscanf(buf, "Name = %s", name) == 1) {
1912 if(!check_id(name)) {
1913 fprintf(stderr, "Invalid Name in input!\n");
1921 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1923 if(!force && !access(filename, F_OK)) {
1924 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1929 out = fopen(filename, "w");
1931 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1937 } else if(firstline) {
1938 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1943 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1947 if(fputs(buf, out) < 0) {
1948 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1958 fprintf(stderr, "Imported %d host configuration files.\n", count);
1961 fprintf(stderr, "No host configuration files imported.\n");
1966 static int cmd_exchange(int argc, char *argv[]) {
1967 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1970 static int cmd_exchange_all(int argc, char *argv[]) {
1971 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1974 static const struct {
1975 const char *command;
1976 int (*function)(int argc, char *argv[]);
1978 {"start", cmd_start},
1980 {"restart", cmd_restart},
1981 {"reload", cmd_reload},
1983 {"purge", cmd_purge},
1984 {"debug", cmd_debug},
1985 {"retry", cmd_retry},
1986 {"connect", cmd_connect},
1987 {"disconnect", cmd_disconnect},
1992 {"config", cmd_config},
1993 {"add", cmd_config},
1994 {"del", cmd_config},
1995 {"get", cmd_config},
1996 {"set", cmd_config},
1997 {"change", cmd_config},
1998 {"replace", cmd_config},
2000 {"generate-keys", cmd_generate_keys},
2001 {"generate-rsa-keys", cmd_generate_rsa_keys},
2002 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2004 {"version", cmd_version},
2007 {"export", cmd_export},
2008 {"export-all", cmd_export_all},
2009 {"import", cmd_import},
2010 {"exchange", cmd_exchange},
2011 {"exchange-all", cmd_exchange_all},
2015 #ifdef HAVE_READLINE
2016 static char *complete_command(const char *text, int state) {
2024 while(commands[i].command) {
2025 if(!strncasecmp(commands[i].command, text, strlen(text)))
2026 return xstrdup(commands[i].command);
2033 static char *complete_dump(const char *text, int state) {
2034 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2043 if(!strncasecmp(matches[i], text, strlen(text)))
2044 return xstrdup(matches[i]);
2051 static char *complete_config(const char *text, int state) {
2052 const char *sub[] = {"get", "set", "add", "del"};
2056 if(!strchr(rl_line_buffer + 7, ' '))
2060 for(int i = 0; i < 4; i++) {
2061 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2073 while(i < 0 || variables[i].name) {
2074 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2075 return xstrdup(sub[i + 4]);
2077 char *dot = strchr(text, '.');
2079 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2081 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2085 if(!strncasecmp(variables[i].name, text, strlen(text)))
2086 return xstrdup(variables[i].name);
2095 static char *complete_info(const char *text, int state) {
2099 if(!connect_tincd(false))
2101 // Check the list of nodes
2102 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2103 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2106 while(recvline(fd, line, sizeof line)) {
2108 int n = sscanf(line, "%d %d %s", &code, &req, item);
2118 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2122 if(!strncmp(item, text, strlen(text)))
2123 return xstrdup(strip_weight(item));
2129 static char *complete_nothing(const char *text, int state) {
2133 static char **completion (const char *text, int start, int end) {
2134 char **matches = NULL;
2137 matches = rl_completion_matches(text, complete_command);
2138 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2139 matches = rl_completion_matches(text, complete_dump);
2140 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2141 matches = rl_completion_matches(text, complete_config);
2142 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2143 matches = rl_completion_matches(text, complete_info);
2149 static int cmd_shell(int argc, char *argv[]) {
2151 xasprintf(&prompt, "%s> ", identname);
2155 int maxargs = argc + 16;
2156 char **nargv = xmalloc(maxargs * sizeof *nargv);
2158 for(int i = 0; i < argc; i++)
2161 #ifdef HAVE_READLINE
2162 rl_readline_name = "tinc";
2163 rl_completion_entry_function = complete_nothing;
2164 rl_attempted_completion_function = completion;
2165 rl_filename_completion_desired = 0;
2170 #ifdef HAVE_READLINE
2174 rl_basic_word_break_characters = "\t\n ";
2175 line = readline(prompt);
2177 copy = xstrdup(line);
2179 line = fgets(buf, sizeof buf, stdin);
2183 fputs(prompt, stdout);
2185 line = fgets(buf, sizeof buf, stdin);
2191 /* Ignore comments */
2199 char *p = line + strspn(line, " \t\n");
2200 char *next = strtok(p, " \t\n");
2203 if(nargc >= maxargs) {
2204 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2207 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2212 next = strtok(NULL, " \t\n");
2218 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2223 for(int i = 0; commands[i].command; i++) {
2224 if(!strcasecmp(nargv[argc], commands[i].command)) {
2225 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2231 #ifdef HAVE_READLINE
2237 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2250 int main(int argc, char *argv[]) {
2251 program_name = argv[0];
2255 if(!parse_options(argc, argv))
2259 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2260 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2272 tty = isatty(0) && isatty(1);
2275 return cmd_shell(argc, argv);
2277 for(int i = 0; commands[i].command; i++) {
2278 if(!strcasecmp(argv[optind], commands[i].command))
2279 return commands[i].function(argc - optind, argv + optind);
2282 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);