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 " config Change configuration:\n"
116 " [get] VARIABLE - print current value of VARIABLE\n"
117 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
118 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
119 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
120 " start [tincd options] Start tincd.\n"
121 " stop Stop tincd.\n"
122 " restart Restart tincd.\n"
123 " reload Partially reload configuration of running tincd.\n"
124 " pid Show PID of currently running tincd.\n"
125 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
126 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
127 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
128 " dump Dump a list of one of the following things:\n"
129 " [reachable] nodes - all known nodes in the VPN\n"
130 " edges - all known connections in the VPN\n"
131 " subnets - all known subnets in the VPN\n"
132 " connections - all meta connections with ourself\n"
133 " [di]graph - graph of the VPN in dotty format\n"
134 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
135 " purge Purge unreachable nodes\n"
136 " debug N Set debug level\n"
137 " retry Retry all outgoing connections\n"
138 " disconnect NODE Close meta connection with NODE\n"
140 " top Show real-time statistics\n"
142 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
143 " log [level] Dump log output [up to the specified level]\n"
144 " export Export host configuration of local node to standard output\n"
145 " export-all Export all host configuration files to standard output\n"
146 " import [--force] Import host configuration file(s) from standard input\n"
147 " exchange [--force] Same as export followed by import\n"
148 " exchange-all [--force] Same as export-all followed by import\n"
150 printf("Report bugs to tinc@tinc-vpn.org.\n");
154 static bool parse_options(int argc, char **argv) {
156 int option_index = 0;
158 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
160 case 0: /* long option */
163 case 'c': /* config file */
164 confbase = xstrdup(optarg);
167 case 'n': /* net name given */
168 netname = xstrdup(optarg);
171 case 1: /* show help */
175 case 2: /* show version */
179 case 5: /* open control socket here */
180 pidfilename = xstrdup(optarg);
187 case '?': /* wrong options */
196 if(!netname && (netname = getenv("NETNAME")))
197 netname = xstrdup(netname);
199 /* netname "." is special: a "top-level name" */
201 if(netname && (!*netname || !strcmp(netname, "."))) {
206 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
207 fprintf(stderr, "Invalid character in netname!\n");
214 static void disable_old_keys(const char *filename, const char *what) {
215 char tmpfile[PATH_MAX] = "";
217 bool disabled = false;
222 r = fopen(filename, "r");
226 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
228 w = fopen(tmpfile, "w");
230 while(fgets(buf, sizeof buf, r)) {
231 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
232 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
238 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
244 if(block || ecdsapubkey)
246 if(fputs(buf, w) < 0) {
252 if(block && !strncmp(buf, "-----END ", 9))
259 if(ferror(r) || fclose(r) < 0)
264 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
271 // We cannot atomically replace files on Windows.
272 char bakfile[PATH_MAX] = "";
273 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
274 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
275 rename(bakfile, filename);
277 if(rename(tmpfile, filename)) {
279 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
284 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
291 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
297 /* Check stdin and stdout */
299 /* Ask for a file and/or directory name. */
300 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
304 if(fgets(buf, sizeof buf, stdin) == NULL) {
305 fprintf(stderr, "Error while reading stdin: %s\n",
310 size_t len = strlen(buf);
319 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
321 if(filename[0] != '/') {
323 /* The directory is a relative path or a filename. */
324 directory = get_current_dir_name();
325 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
329 umask(0077); /* Disallow everything for group and other */
331 disable_old_keys(filename, what);
333 /* Open it first to keep the inode busy */
335 r = fopen(filename, mode);
338 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
346 Generate a public/private ECDSA keypair, and ask for a file to store
349 static bool ecdsa_keygen(bool ask) {
352 char *pubname, *privname;
354 fprintf(stderr, "Generating ECDSA keypair:\n");
356 if(!ecdsa_generate(&key)) {
357 fprintf(stderr, "Error during key generation!\n");
360 fprintf(stderr, "Done.\n");
362 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
363 f = ask_and_open(privname, "private ECDSA key", "a", ask);
370 /* Make it unreadable for others. */
371 fchmod(fileno(f), 0600);
374 ecdsa_write_pem_private_key(&key, f);
379 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
381 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
383 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
389 char *pubkey = ecdsa_get_base64_public_key(&key);
390 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
399 Generate a public/private RSA keypair, and ask for a file to store
402 static bool rsa_keygen(int bits, bool ask) {
405 char *pubname, *privname;
407 fprintf(stderr, "Generating %d bits keys:\n", bits);
409 if(!rsa_generate(&key, bits, 0x10001)) {
410 fprintf(stderr, "Error during key generation!\n");
413 fprintf(stderr, "Done.\n");
415 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
416 f = ask_and_open(privname, "private RSA key", "a", ask);
423 /* Make it unreadable for others. */
424 fchmod(fileno(f), 0600);
427 rsa_write_pem_private_key(&key, f);
432 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
434 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
436 f = ask_and_open(pubname, "public RSA key", "a", ask);
442 rsa_write_pem_public_key(&key, f);
449 static char buffer[4096];
450 static size_t blen = 0;
452 bool recvline(int fd, char *line, size_t len) {
453 char *newline = NULL;
455 while(!(newline = memchr(buffer, '\n', blen))) {
456 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
457 if(result == -1 && errno == EINTR)
464 if(newline - buffer >= len)
467 len = newline - buffer;
469 memcpy(line, buffer, len);
471 memmove(buffer, newline + 1, blen - len - 1);
477 static bool recvdata(int fd, char *data, size_t len) {
479 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
480 if(result == -1 && errno == EINTR)
487 memcpy(data, buffer, len);
488 memmove(buffer, buffer + len, blen - len);
494 bool sendline(int fd, char *format, ...) {
495 static char buffer[4096];
500 va_start(ap, format);
501 blen = vsnprintf(buffer, sizeof buffer, format, ap);
504 if(blen < 1 || blen >= sizeof buffer)
511 int result = send(fd, p, blen, 0);
512 if(result == -1 && errno == EINTR)
523 static void pcap(int fd, FILE *out, int snaplen) {
524 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
532 uint32_t tz_accuracy;
539 snaplen ?: sizeof data,
552 fwrite(&header, sizeof header, 1, out);
556 while(recvline(fd, line, sizeof line)) {
558 int n = sscanf(line, "%d %d %d", &code, &req, &len);
559 gettimeofday(&tv, NULL);
560 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
562 if(!recvdata(fd, data, len))
564 packet.tv_sec = tv.tv_sec;
565 packet.tv_usec = tv.tv_usec;
567 packet.origlen = len;
568 fwrite(&packet, sizeof packet, 1, out);
569 fwrite(data, len, 1, out);
574 static void logcontrol(int fd, FILE *out, int level) {
575 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
579 while(recvline(fd, line, sizeof line)) {
581 int n = sscanf(line, "%d %d %d", &code, &req, &len);
582 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
584 if(!recvdata(fd, data, len))
586 fwrite(data, len, 1, out);
593 static bool remove_service(void) {
594 SC_HANDLE manager = NULL;
595 SC_HANDLE service = NULL;
596 SERVICE_STATUS status = {0};
598 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
600 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
604 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
607 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
611 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
612 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
614 fprintf(stderr, "%s service stopped\n", identname);
616 if(!DeleteService(service)) {
617 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
621 fprintf(stderr, "%s service removed\n", identname);
627 static bool connect_tincd(bool verbose) {
632 struct timeval tv = {0, 0};
633 if(select(fd + 1, &r, NULL, NULL, &tv)) {
634 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
642 FILE *f = fopen(pidfilename, "r");
645 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
652 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
654 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
662 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
664 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
670 struct sockaddr_un sa;
671 sa.sun_family = AF_UNIX;
672 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
674 fd = socket(AF_UNIX, SOCK_STREAM, 0);
677 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
681 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
683 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
689 struct addrinfo hints = {
690 .ai_family = AF_UNSPEC,
691 .ai_socktype = SOCK_STREAM,
692 .ai_protocol = IPPROTO_TCP,
696 struct addrinfo *res = NULL;
698 if(getaddrinfo(host, port, &hints, &res) || !res) {
700 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
704 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
707 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
712 unsigned long arg = 0;
714 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
716 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
720 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
722 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
734 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
736 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
742 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
744 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
746 fprintf(stderr, "Could not fully establish control socket connection\n");
756 static int cmd_start(int argc, char *argv[]) {
757 if(connect_tincd(false)) {
759 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
761 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
766 char *slash = strrchr(program_name, '/');
769 if ((c = strrchr(program_name, '\\')) > slash)
774 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
779 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
782 for(int i = 1; i < optind; i++)
783 nargv[nargc++] = orig_argv[i];
784 for(int i = 1; i < argc; i++)
785 nargv[nargc++] = argv[i];
789 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
794 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
800 exit(execvp(c, nargv));
805 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
806 fprintf(stderr, "Error starting %s\n", c);
814 static int cmd_stop(int argc, char *argv[]) {
816 fprintf(stderr, "Too many arguments!\n");
821 if(!connect_tincd(true)) {
823 if(kill(pid, SIGTERM)) {
824 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
828 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
829 waitpid(pid, NULL, 0);
836 sendline(fd, "%d %d", CONTROL, REQ_STOP);
837 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
838 fprintf(stderr, "Could not stop tinc daemon.\n");
842 // Wait for tincd to close the connection...
846 select(fd + 1, &r, NULL, NULL, NULL);
848 if(!remove_service())
858 static int cmd_restart(int argc, char *argv[]) {
859 cmd_stop(argc, argv);
860 return cmd_start(argc, argv);
863 static int cmd_reload(int argc, char *argv[]) {
865 fprintf(stderr, "Too many arguments!\n");
869 if(!connect_tincd(true))
872 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
873 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
874 fprintf(stderr, "Could not reload configuration.\n");
882 static int cmd_dump(int argc, char *argv[]) {
883 bool only_reachable = false;
885 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
886 if(strcasecmp(argv[2], "nodes")) {
887 fprintf(stderr, "`reachable' only supported for nodes.\n");
891 only_reachable = true;
897 fprintf(stderr, "Invalid number of arguments.\n");
902 if(!connect_tincd(true))
907 if(!strcasecmp(argv[1], "nodes"))
908 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
909 else if(!strcasecmp(argv[1], "edges"))
910 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
911 else if(!strcasecmp(argv[1], "subnets"))
912 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
913 else if(!strcasecmp(argv[1], "connections"))
914 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
915 else if(!strcasecmp(argv[1], "graph")) {
916 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
917 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
919 } else if(!strcasecmp(argv[1], "digraph")) {
920 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
921 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
924 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
931 else if(do_graph == 2)
932 printf("digraph {\n");
934 while(recvline(fd, line, sizeof line)) {
935 char node1[4096], node2[4096];
936 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
938 if(do_graph && req == REQ_DUMP_NODES)
957 int cipher, digest, maclength, compression, distance, socket, weight;
958 short int pmtu, minmtu, maxmtu;
959 unsigned int options, status_int;
960 node_status_t status;
961 long int last_state_change;
964 case REQ_DUMP_NODES: {
965 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);
967 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
971 memcpy(&status, &status_int, sizeof status);
974 const char *color = "black";
975 if(!strcmp(host, "MYSELF"))
977 else if(!status.reachable)
979 else if(strcmp(via, node))
981 else if(!status.validkey)
985 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
987 if(only_reachable && !status.reachable)
989 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",
990 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
994 case REQ_DUMP_EDGES: {
995 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
997 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1002 float w = 1 + 65536.0 / weight;
1003 if(do_graph == 1 && strcmp(node1, node2) > 0)
1004 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1005 else if(do_graph == 2)
1006 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1008 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1012 case REQ_DUMP_SUBNETS: {
1013 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1015 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1018 printf("%s owner %s\n", strip_weight(subnet), node);
1021 case REQ_DUMP_CONNECTIONS: {
1022 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1024 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1027 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1031 fprintf(stderr, "Unable to parse dump from tincd.\n");
1036 fprintf(stderr, "Error receiving dump.\n");
1040 static int cmd_purge(int argc, char *argv[]) {
1042 fprintf(stderr, "Too many arguments!\n");
1046 if(!connect_tincd(true))
1049 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1050 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1051 fprintf(stderr, "Could not purge old information.\n");
1058 static int cmd_debug(int argc, char *argv[]) {
1060 fprintf(stderr, "Invalid number of arguments.\n");
1064 if(!connect_tincd(true))
1067 int debuglevel = atoi(argv[1]);
1070 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1071 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1072 fprintf(stderr, "Could not set debug level.\n");
1076 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1080 static int cmd_retry(int argc, char *argv[]) {
1082 fprintf(stderr, "Too many arguments!\n");
1086 if(!connect_tincd(true))
1089 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1090 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1091 fprintf(stderr, "Could not retry outgoing connections.\n");
1098 static int cmd_connect(int argc, char *argv[]) {
1100 fprintf(stderr, "Invalid number of arguments.\n");
1104 if(!check_id(argv[1])) {
1105 fprintf(stderr, "Invalid name for node.\n");
1109 if(!connect_tincd(true))
1112 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1113 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1114 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1121 static int cmd_disconnect(int argc, char *argv[]) {
1123 fprintf(stderr, "Invalid number of arguments.\n");
1127 if(!check_id(argv[1])) {
1128 fprintf(stderr, "Invalid name for node.\n");
1132 if(!connect_tincd(true))
1135 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1136 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1137 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1144 static int cmd_top(int argc, char *argv[]) {
1146 fprintf(stderr, "Too many arguments!\n");
1151 if(!connect_tincd(true))
1157 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1162 static int cmd_pcap(int argc, char *argv[]) {
1164 fprintf(stderr, "Too many arguments!\n");
1168 if(!connect_tincd(true))
1171 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1175 static int cmd_log(int argc, char *argv[]) {
1177 fprintf(stderr, "Too many arguments!\n");
1181 if(!connect_tincd(true))
1184 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1188 static int cmd_pid(int argc, char *argv[]) {
1190 fprintf(stderr, "Too many arguments!\n");
1194 if(!connect_tincd(true) && !pid)
1197 printf("%d\n", pid);
1201 static int rstrip(char *value) {
1202 int len = strlen(value);
1203 while(len && strchr("\t\r\n ", value[len - 1]))
1208 static char *get_my_name() {
1209 FILE *f = fopen(tinc_conf, "r");
1211 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1217 while(fgets(buf, sizeof buf, f)) {
1218 int len = strcspn(buf, "\t =");
1220 value += strspn(value, "\t ");
1223 value += strspn(value, "\t ");
1228 if(strcasecmp(buf, "Name"))
1232 return strdup(value);
1237 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1241 #define VAR_SERVER 1 /* Should be in tinc.conf */
1242 #define VAR_HOST 2 /* Can be in host config file */
1243 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1244 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1249 } const variables[] = {
1250 /* Server configuration */
1251 {"AddressFamily", VAR_SERVER},
1252 {"AutoConnect", VAR_SERVER},
1253 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1254 {"BindToInterface", VAR_SERVER},
1255 {"Broadcast", VAR_SERVER},
1256 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1257 {"DecrementTTL", VAR_SERVER},
1258 {"Device", VAR_SERVER},
1259 {"DeviceType", VAR_SERVER},
1260 {"DirectOnly", VAR_SERVER},
1261 {"ECDSAPrivateKeyFile", VAR_SERVER},
1262 {"ExperimentalProtocol", VAR_SERVER},
1263 {"Forwarding", VAR_SERVER},
1264 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1265 {"Hostnames", VAR_SERVER},
1266 {"IffOneQueue", VAR_SERVER},
1267 {"Interface", VAR_SERVER},
1268 {"KeyExpire", VAR_SERVER},
1269 {"LocalDiscovery", VAR_SERVER},
1270 {"MACExpire", VAR_SERVER},
1271 {"MaxOutputBufferSize", VAR_SERVER},
1272 {"MaxTimeout", VAR_SERVER},
1273 {"Mode", VAR_SERVER},
1274 {"Name", VAR_SERVER},
1275 {"PingInterval", VAR_SERVER},
1276 {"PingTimeout", VAR_SERVER},
1277 {"PriorityInheritance", VAR_SERVER},
1278 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1279 {"PrivateKeyFile", VAR_SERVER},
1280 {"ProcessPriority", VAR_SERVER},
1281 {"Proxy", VAR_SERVER},
1282 {"ReplayWindow", VAR_SERVER},
1283 {"ScriptsExtension", VAR_SERVER},
1284 {"ScriptsInterpreter", VAR_SERVER},
1285 {"StrictSubnets", VAR_SERVER},
1286 {"TunnelServer", VAR_SERVER},
1287 {"UDPRcvBuf", VAR_SERVER},
1288 {"UDPSndBuf", VAR_SERVER},
1289 {"VDEGroup", VAR_SERVER},
1290 {"VDEPort", VAR_SERVER},
1291 /* Host configuration */
1292 {"Address", VAR_HOST | VAR_MULTIPLE},
1293 {"Cipher", VAR_SERVER | VAR_HOST},
1294 {"ClampMSS", VAR_SERVER | VAR_HOST},
1295 {"Compression", VAR_SERVER | VAR_HOST},
1296 {"Digest", VAR_SERVER | VAR_HOST},
1297 {"ECDSAPublicKey", VAR_HOST},
1298 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1299 {"IndirectData", VAR_SERVER | VAR_HOST},
1300 {"MACLength", VAR_SERVER | VAR_HOST},
1301 {"PMTU", VAR_SERVER | VAR_HOST},
1302 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1304 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1305 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1306 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1307 {"TCPOnly", VAR_SERVER | VAR_HOST},
1308 {"Weight", VAR_HOST},
1312 static int cmd_config(int argc, char *argv[]) {
1314 fprintf(stderr, "Invalid number of arguments.\n");
1319 if(!strcasecmp(argv[1], "get")) {
1321 } else if(!strcasecmp(argv[1], "add")) {
1322 argv++, argc--, action = 1;
1323 } else if(!strcasecmp(argv[1], "del")) {
1324 argv++, argc--, action = -1;
1325 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1326 argv++, argc--, action = 0;
1330 fprintf(stderr, "Invalid number of arguments.\n");
1334 // Concatenate the rest of the command line
1335 strncpy(line, argv[1], sizeof line - 1);
1336 for(int i = 2; i < argc; i++) {
1337 strncat(line, " ", sizeof line - 1 - strlen(line));
1338 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1341 // Liberal parsing into node name, variable name and value.
1347 len = strcspn(line, "\t =");
1349 value += strspn(value, "\t ");
1352 value += strspn(value, "\t ");
1355 variable = strchr(line, '.');
1364 fprintf(stderr, "No variable given.\n");
1368 if(action >= 0 && !*value) {
1369 fprintf(stderr, "No value for variable given.\n");
1373 if(action < -1 && *value)
1376 /* Some simple checks. */
1379 for(int i = 0; variables[i].name; i++) {
1380 if(strcasecmp(variables[i].name, variable))
1384 variable = (char *)variables[i].name;
1386 /* Discourage use of obsolete variables. */
1388 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1390 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1392 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1397 /* Don't put server variables in host config files */
1399 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1401 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1403 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1408 /* Should this go into our own host config file? */
1410 if(!node && !(variables[i].type & VAR_SERVER)) {
1411 node = get_my_name();
1419 if(node && !check_id(node)) {
1420 fprintf(stderr, "Invalid name for node.\n");
1425 if(force || action < 0) {
1426 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1428 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1433 // Open the right configuration file.
1436 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1438 filename = tinc_conf;
1440 FILE *f = fopen(filename, "r");
1442 if(action < 0 || errno != ENOENT) {
1443 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1447 // If it doesn't exist, create it.
1448 f = fopen(filename, "a+");
1450 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1453 fprintf(stderr, "Created configuration file %s.\n", filename);
1457 char *tmpfile = NULL;
1461 xasprintf(&tmpfile, "%s.config.tmp", filename);
1462 tf = fopen(tmpfile, "w");
1464 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1470 // Copy the file, making modifications on the fly, unless we are just getting a value.
1474 bool removed = false;
1477 while(fgets(buf1, sizeof buf1, f)) {
1478 buf1[sizeof buf1 - 1] = 0;
1479 strncpy(buf2, buf1, sizeof buf2);
1481 // Parse line in a simple way
1485 len = strcspn(buf2, "\t =");
1486 bvalue = buf2 + len;
1487 bvalue += strspn(bvalue, "\t ");
1488 if(*bvalue == '=') {
1490 bvalue += strspn(bvalue, "\t ");
1496 if(!strcasecmp(buf2, variable)) {
1500 printf("%s\n", bvalue);
1502 } else if(action == -1) {
1503 if(!*value || !strcasecmp(bvalue, value)) {
1508 } else if(action == 0) {
1509 // Already set? Delete the rest...
1512 // Otherwise, replace.
1513 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1514 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1523 // Copy original line...
1524 if(fputs(buf1, tf) < 0) {
1525 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1529 // Add newline if it is missing...
1530 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1531 if(fputc('\n', tf) < 0) {
1532 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1539 // Make sure we read everything...
1540 if(ferror(f) || !feof(f)) {
1541 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1546 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1550 // Add new variable if necessary.
1551 if(action > 0 || (action == 0 && !set)) {
1552 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1553 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1560 fprintf(stderr, "No matching configuration variables found.\n");
1564 // Make sure we wrote everything...
1566 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1570 // Could we find what we had to remove?
1571 if(action < 0 && !removed) {
1573 fprintf(stderr, "No configuration variables deleted.\n");
1577 // Replace the configuration file with the new one
1579 if(remove(filename)) {
1580 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1584 if(rename(tmpfile, filename)) {
1585 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1589 // Silently try notifying a running tincd of changes.
1590 if(connect_tincd(false))
1591 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1596 bool check_id(const char *name) {
1600 for(int i = 0; i < strlen(name); i++) {
1601 if(!isalnum(name[i]) && name[i] != '_')
1608 static int cmd_init(int argc, char *argv[]) {
1609 if(!access(tinc_conf, F_OK)) {
1610 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1615 fprintf(stderr, "Too many arguments!\n");
1617 } else if(argc < 2) {
1620 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1622 if(!fgets(buf, sizeof buf, stdin)) {
1623 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1626 int len = rstrip(buf);
1628 fprintf(stderr, "No name given!\n");
1633 fprintf(stderr, "No Name given!\n");
1637 name = strdup(argv[1]);
1639 fprintf(stderr, "No Name given!\n");
1644 if(!check_id(name)) {
1645 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1649 if(mkdir(confdir, 0755) && errno != EEXIST) {
1650 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1654 if(mkdir(confbase, 0755) && errno != EEXIST) {
1655 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1659 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1660 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1664 FILE *f = fopen(tinc_conf, "w");
1666 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1670 fprintf(f, "Name = %s\n", name);
1673 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1678 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1679 if(access(filename, F_OK)) {
1680 FILE *f = fopen(filename, "w");
1682 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1685 fchmod(fileno(f), 0755);
1686 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");
1695 static int cmd_generate_keys(int argc, char *argv[]) {
1697 fprintf(stderr, "Too many arguments!\n");
1701 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1704 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1706 fprintf(stderr, "Too many arguments!\n");
1710 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1713 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1715 fprintf(stderr, "Too many arguments!\n");
1719 return !ecdsa_keygen(true);
1722 static int cmd_help(int argc, char *argv[]) {
1727 static int cmd_version(int argc, char *argv[]) {
1729 fprintf(stderr, "Too many arguments!\n");
1737 static int cmd_info(int argc, char *argv[]) {
1739 fprintf(stderr, "Invalid number of arguments.\n");
1743 if(!connect_tincd(true))
1746 return info(fd, argv[1]);
1749 static const char *conffiles[] = {
1760 static int cmd_edit(int argc, char *argv[]) {
1762 fprintf(stderr, "Invalid number of arguments.\n");
1766 char *filename = NULL;
1768 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1769 for(int i = 0; conffiles[i]; i++) {
1770 if(!strcmp(argv[1], conffiles[i])) {
1771 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1780 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1781 char *dash = strchr(argv[1], '-');
1784 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1785 fprintf(stderr, "Invalid configuration filename.\n");
1793 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1795 xasprintf(&command, "edit \"%s\"", filename);
1797 int result = system(command);
1801 // Silently try notifying a running tincd of changes.
1802 if(connect_tincd(false))
1803 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1808 static int export(const char *name, FILE *out) {
1810 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1811 FILE *in = fopen(filename, "r");
1813 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1817 fprintf(out, "Name = %s\n", name);
1819 while(fgets(buf, sizeof buf, in)) {
1820 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1825 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1834 static int cmd_export(int argc, char *argv[]) {
1836 fprintf(stderr, "Too many arguments!\n");
1840 char *name = get_my_name();
1844 int result = export(name, stdout);
1850 static int cmd_export_all(int argc, char *argv[]) {
1852 fprintf(stderr, "Too many arguments!\n");
1856 DIR *dir = opendir(hosts_dir);
1858 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1866 while((ent = readdir(dir))) {
1867 if(!check_id(ent->d_name))
1873 printf("#---------------------------------------------------------------#\n");
1875 result |= export(ent->d_name, stdout);
1884 static int cmd_import(int argc, char *argv[]) {
1886 fprintf(stderr, "Too many arguments!\n");
1895 char *filename = NULL;
1897 bool firstline = true;
1899 while(fgets(buf, sizeof buf, in)) {
1900 if(sscanf(buf, "Name = %s", name) == 1) {
1903 if(!check_id(name)) {
1904 fprintf(stderr, "Invalid Name in input!\n");
1912 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1914 if(!force && !access(filename, F_OK)) {
1915 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1920 out = fopen(filename, "w");
1922 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1928 } else if(firstline) {
1929 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1934 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1938 if(fputs(buf, out) < 0) {
1939 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1949 fprintf(stderr, "Imported %d host configuration files.\n", count);
1952 fprintf(stderr, "No host configuration files imported.\n");
1957 static int cmd_exchange(int argc, char *argv[]) {
1958 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1961 static int cmd_exchange_all(int argc, char *argv[]) {
1962 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1965 static const struct {
1966 const char *command;
1967 int (*function)(int argc, char *argv[]);
1969 {"start", cmd_start},
1971 {"restart", cmd_restart},
1972 {"reload", cmd_reload},
1974 {"purge", cmd_purge},
1975 {"debug", cmd_debug},
1976 {"retry", cmd_retry},
1977 {"connect", cmd_connect},
1978 {"disconnect", cmd_disconnect},
1983 {"config", cmd_config},
1985 {"generate-keys", cmd_generate_keys},
1986 {"generate-rsa-keys", cmd_generate_rsa_keys},
1987 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1989 {"version", cmd_version},
1992 {"export", cmd_export},
1993 {"export-all", cmd_export_all},
1994 {"import", cmd_import},
1995 {"exchange", cmd_exchange},
1996 {"exchange-all", cmd_exchange_all},
2000 #ifdef HAVE_READLINE
2001 static char *complete_command(const char *text, int state) {
2009 while(commands[i].command) {
2010 if(!strncasecmp(commands[i].command, text, strlen(text)))
2011 return xstrdup(commands[i].command);
2018 static char *complete_dump(const char *text, int state) {
2019 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2028 if(!strncasecmp(matches[i], text, strlen(text)))
2029 return xstrdup(matches[i]);
2036 static char *complete_config(const char *text, int state) {
2037 const char *sub[] = {"get", "set", "add", "del"};
2041 if(!strchr(rl_line_buffer + 7, ' '))
2045 for(int i = 0; i < 4; i++) {
2046 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2058 while(i < 0 || variables[i].name) {
2059 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2060 return xstrdup(sub[i + 4]);
2062 char *dot = strchr(text, '.');
2064 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2066 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2070 if(!strncasecmp(variables[i].name, text, strlen(text)))
2071 return xstrdup(variables[i].name);
2080 static char *complete_info(const char *text, int state) {
2084 if(!connect_tincd(false))
2086 // Check the list of nodes
2087 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2088 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2091 while(recvline(fd, line, sizeof line)) {
2093 int n = sscanf(line, "%d %d %s", &code, &req, item);
2103 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2107 if(!strncmp(item, text, strlen(text)))
2108 return xstrdup(strip_weight(item));
2114 static char *complete_nothing(const char *text, int state) {
2118 static char **completion (const char *text, int start, int end) {
2119 char **matches = NULL;
2122 matches = rl_completion_matches(text, complete_command);
2123 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2124 matches = rl_completion_matches(text, complete_dump);
2125 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2126 matches = rl_completion_matches(text, complete_config);
2127 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2128 matches = rl_completion_matches(text, complete_info);
2134 static int cmd_shell(int argc, char *argv[]) {
2136 xasprintf(&prompt, "%s> ", identname);
2140 int maxargs = argc + 16;
2141 char **nargv = xmalloc(maxargs * sizeof *nargv);
2143 for(int i = 0; i < argc; i++)
2146 #ifdef HAVE_READLINE
2147 rl_readline_name = "tinc";
2148 rl_completion_entry_function = complete_nothing;
2149 rl_attempted_completion_function = completion;
2150 rl_filename_completion_desired = 0;
2155 #ifdef HAVE_READLINE
2159 rl_basic_word_break_characters = "\t\n ";
2160 line = readline(prompt);
2162 copy = xstrdup(line);
2164 line = fgets(buf, sizeof buf, stdin);
2168 fputs(prompt, stdout);
2170 line = fgets(buf, sizeof buf, stdin);
2176 /* Ignore comments */
2184 char *p = line + strspn(line, " \t\n");
2185 char *next = strtok(p, " \t\n");
2188 if(nargc >= maxargs) {
2189 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2192 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2197 next = strtok(NULL, " \t\n");
2203 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2208 for(int i = 0; commands[i].command; i++) {
2209 if(!strcasecmp(nargv[argc], commands[i].command)) {
2210 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2216 #ifdef HAVE_READLINE
2222 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2235 int main(int argc, char *argv[]) {
2236 program_name = argv[0];
2240 if(!parse_options(argc, argv))
2244 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2245 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2257 tty = isatty(0) && isatty(1);
2260 return cmd_shell(argc, argv);
2262 for(int i = 0; commands[i].command; i++) {
2263 if(!strcasecmp(argv[optind], commands[i].command))
2264 return commands[i].function(argc - optind, argv + optind);
2267 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);