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);
838 while(recvline(fd, line, sizeof line)) {
839 // Wait for tincd to close the connection...
842 if(!remove_service())
852 static int cmd_restart(int argc, char *argv[]) {
853 cmd_stop(argc, argv);
854 return cmd_start(argc, argv);
857 static int cmd_reload(int argc, char *argv[]) {
859 fprintf(stderr, "Too many arguments!\n");
863 if(!connect_tincd(true))
866 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
867 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
868 fprintf(stderr, "Could not reload configuration.\n");
876 static int cmd_dump(int argc, char *argv[]) {
877 bool only_reachable = false;
879 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
880 if(strcasecmp(argv[2], "nodes")) {
881 fprintf(stderr, "`reachable' only supported for nodes.\n");
885 only_reachable = true;
891 fprintf(stderr, "Invalid number of arguments.\n");
896 if(!connect_tincd(true))
901 if(!strcasecmp(argv[1], "nodes"))
902 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
903 else if(!strcasecmp(argv[1], "edges"))
904 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
905 else if(!strcasecmp(argv[1], "subnets"))
906 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
907 else if(!strcasecmp(argv[1], "connections"))
908 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
909 else if(!strcasecmp(argv[1], "graph")) {
910 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
911 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
913 } else if(!strcasecmp(argv[1], "digraph")) {
914 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
915 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
918 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
925 else if(do_graph == 2)
926 printf("digraph {\n");
928 while(recvline(fd, line, sizeof line)) {
929 char node1[4096], node2[4096];
930 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
932 if(do_graph && req == REQ_DUMP_NODES)
951 int cipher, digest, maclength, compression, distance, socket, weight;
952 short int pmtu, minmtu, maxmtu;
953 unsigned int options, status_int;
954 node_status_t status;
955 long int last_state_change;
958 case REQ_DUMP_NODES: {
959 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);
961 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
965 memcpy(&status, &status_int, sizeof status);
968 const char *color = "black";
969 if(!strcmp(host, "MYSELF"))
971 else if(!status.reachable)
973 else if(strcmp(via, node))
975 else if(!status.validkey)
979 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
981 if(only_reachable && !status.reachable)
983 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",
984 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
988 case REQ_DUMP_EDGES: {
989 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
991 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
996 float w = 1 + 65536.0 / weight;
997 if(do_graph == 1 && strcmp(node1, node2) > 0)
998 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
999 else if(do_graph == 2)
1000 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1002 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1006 case REQ_DUMP_SUBNETS: {
1007 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1009 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1012 printf("%s owner %s\n", strip_weight(subnet), node);
1015 case REQ_DUMP_CONNECTIONS: {
1016 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1018 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1021 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1025 fprintf(stderr, "Unable to parse dump from tincd.\n");
1030 fprintf(stderr, "Error receiving dump.\n");
1034 static int cmd_purge(int argc, char *argv[]) {
1036 fprintf(stderr, "Too many arguments!\n");
1040 if(!connect_tincd(true))
1043 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1044 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1045 fprintf(stderr, "Could not purge old information.\n");
1052 static int cmd_debug(int argc, char *argv[]) {
1054 fprintf(stderr, "Invalid number of arguments.\n");
1058 if(!connect_tincd(true))
1061 int debuglevel = atoi(argv[1]);
1064 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1065 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1066 fprintf(stderr, "Could not set debug level.\n");
1070 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1074 static int cmd_retry(int argc, char *argv[]) {
1076 fprintf(stderr, "Too many arguments!\n");
1080 if(!connect_tincd(true))
1083 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1084 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1085 fprintf(stderr, "Could not retry outgoing connections.\n");
1092 static int cmd_connect(int argc, char *argv[]) {
1094 fprintf(stderr, "Invalid number of arguments.\n");
1098 if(!check_id(argv[1])) {
1099 fprintf(stderr, "Invalid name for node.\n");
1103 if(!connect_tincd(true))
1106 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1107 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1108 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1115 static int cmd_disconnect(int argc, char *argv[]) {
1117 fprintf(stderr, "Invalid number of arguments.\n");
1121 if(!check_id(argv[1])) {
1122 fprintf(stderr, "Invalid name for node.\n");
1126 if(!connect_tincd(true))
1129 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1130 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1131 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1138 static int cmd_top(int argc, char *argv[]) {
1140 fprintf(stderr, "Too many arguments!\n");
1145 if(!connect_tincd(true))
1151 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1156 static int cmd_pcap(int argc, char *argv[]) {
1158 fprintf(stderr, "Too many arguments!\n");
1162 if(!connect_tincd(true))
1165 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1169 static int cmd_log(int argc, char *argv[]) {
1171 fprintf(stderr, "Too many arguments!\n");
1175 if(!connect_tincd(true))
1178 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1182 static int cmd_pid(int argc, char *argv[]) {
1184 fprintf(stderr, "Too many arguments!\n");
1188 if(!connect_tincd(true) && !pid)
1191 printf("%d\n", pid);
1195 static int rstrip(char *value) {
1196 int len = strlen(value);
1197 while(len && strchr("\t\r\n ", value[len - 1]))
1202 static char *get_my_name() {
1203 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);
1231 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1235 #define VAR_SERVER 1 /* Should be in tinc.conf */
1236 #define VAR_HOST 2 /* Can be in host config file */
1237 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1238 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1243 } const variables[] = {
1244 /* Server configuration */
1245 {"AddressFamily", VAR_SERVER},
1246 {"AutoConnect", VAR_SERVER},
1247 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1248 {"BindToInterface", VAR_SERVER},
1249 {"Broadcast", VAR_SERVER},
1250 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1251 {"DecrementTTL", VAR_SERVER},
1252 {"Device", VAR_SERVER},
1253 {"DeviceType", VAR_SERVER},
1254 {"DirectOnly", VAR_SERVER},
1255 {"ECDSAPrivateKeyFile", VAR_SERVER},
1256 {"ExperimentalProtocol", VAR_SERVER},
1257 {"Forwarding", VAR_SERVER},
1258 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1259 {"Hostnames", VAR_SERVER},
1260 {"IffOneQueue", VAR_SERVER},
1261 {"Interface", VAR_SERVER},
1262 {"KeyExpire", VAR_SERVER},
1263 {"LocalDiscovery", VAR_SERVER},
1264 {"MACExpire", VAR_SERVER},
1265 {"MaxOutputBufferSize", VAR_SERVER},
1266 {"MaxTimeout", VAR_SERVER},
1267 {"Mode", VAR_SERVER},
1268 {"Name", VAR_SERVER},
1269 {"PingInterval", VAR_SERVER},
1270 {"PingTimeout", VAR_SERVER},
1271 {"PriorityInheritance", VAR_SERVER},
1272 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1273 {"PrivateKeyFile", VAR_SERVER},
1274 {"ProcessPriority", VAR_SERVER},
1275 {"Proxy", VAR_SERVER},
1276 {"ReplayWindow", VAR_SERVER},
1277 {"ScriptsExtension", VAR_SERVER},
1278 {"ScriptsInterpreter", VAR_SERVER},
1279 {"StrictSubnets", VAR_SERVER},
1280 {"TunnelServer", VAR_SERVER},
1281 {"UDPRcvBuf", VAR_SERVER},
1282 {"UDPSndBuf", VAR_SERVER},
1283 {"VDEGroup", VAR_SERVER},
1284 {"VDEPort", VAR_SERVER},
1285 /* Host configuration */
1286 {"Address", VAR_HOST | VAR_MULTIPLE},
1287 {"Cipher", VAR_SERVER | VAR_HOST},
1288 {"ClampMSS", VAR_SERVER | VAR_HOST},
1289 {"Compression", VAR_SERVER | VAR_HOST},
1290 {"Digest", VAR_SERVER | VAR_HOST},
1291 {"ECDSAPublicKey", VAR_HOST},
1292 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1293 {"IndirectData", VAR_SERVER | VAR_HOST},
1294 {"MACLength", VAR_SERVER | VAR_HOST},
1295 {"PMTU", VAR_SERVER | VAR_HOST},
1296 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1298 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1299 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1300 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1301 {"TCPOnly", VAR_SERVER | VAR_HOST},
1302 {"Weight", VAR_HOST},
1306 static int cmd_config(int argc, char *argv[]) {
1308 fprintf(stderr, "Invalid number of arguments.\n");
1313 if(!strcasecmp(argv[1], "get")) {
1315 } else if(!strcasecmp(argv[1], "add")) {
1316 argv++, argc--, action = 1;
1317 } else if(!strcasecmp(argv[1], "del")) {
1318 argv++, argc--, action = -1;
1319 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1320 argv++, argc--, action = 0;
1324 fprintf(stderr, "Invalid number of arguments.\n");
1328 // Concatenate the rest of the command line
1329 strncpy(line, argv[1], sizeof line - 1);
1330 for(int i = 2; i < argc; i++) {
1331 strncat(line, " ", sizeof line - 1 - strlen(line));
1332 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1335 // Liberal parsing into node name, variable name and value.
1341 len = strcspn(line, "\t =");
1343 value += strspn(value, "\t ");
1346 value += strspn(value, "\t ");
1349 variable = strchr(line, '.');
1358 fprintf(stderr, "No variable given.\n");
1362 if(action >= 0 && !*value) {
1363 fprintf(stderr, "No value for variable given.\n");
1367 if(action < -1 && *value)
1370 /* Some simple checks. */
1373 for(int i = 0; variables[i].name; i++) {
1374 if(strcasecmp(variables[i].name, variable))
1378 variable = (char *)variables[i].name;
1380 /* Discourage use of obsolete variables. */
1382 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1384 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1386 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1391 /* Don't put server variables in host config files */
1393 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1395 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1397 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1402 /* Should this go into our own host config file? */
1404 if(!node && !(variables[i].type & VAR_SERVER)) {
1405 node = get_my_name();
1413 if(node && !check_id(node)) {
1414 fprintf(stderr, "Invalid name for node.\n");
1419 if(force || action < 0) {
1420 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1422 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1427 // Open the right configuration file.
1430 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1432 filename = tinc_conf;
1434 FILE *f = fopen(filename, "r");
1436 if(action < 0 || errno != ENOENT) {
1437 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1441 // If it doesn't exist, create it.
1442 f = fopen(filename, "a+");
1444 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1447 fprintf(stderr, "Created configuration file %s.\n", filename);
1451 char *tmpfile = NULL;
1455 xasprintf(&tmpfile, "%s.config.tmp", filename);
1456 tf = fopen(tmpfile, "w");
1458 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1464 // Copy the file, making modifications on the fly, unless we are just getting a value.
1468 bool removed = false;
1471 while(fgets(buf1, sizeof buf1, f)) {
1472 buf1[sizeof buf1 - 1] = 0;
1473 strncpy(buf2, buf1, sizeof buf2);
1475 // Parse line in a simple way
1479 len = strcspn(buf2, "\t =");
1480 bvalue = buf2 + len;
1481 bvalue += strspn(bvalue, "\t ");
1482 if(*bvalue == '=') {
1484 bvalue += strspn(bvalue, "\t ");
1490 if(!strcasecmp(buf2, variable)) {
1494 printf("%s\n", bvalue);
1496 } else if(action == -1) {
1497 if(!*value || !strcasecmp(bvalue, value)) {
1502 } else if(action == 0) {
1503 // Already set? Delete the rest...
1506 // Otherwise, replace.
1507 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1508 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1517 // Copy original line...
1518 if(fputs(buf1, tf) < 0) {
1519 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1523 // Add newline if it is missing...
1524 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1525 if(fputc('\n', tf) < 0) {
1526 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1533 // Make sure we read everything...
1534 if(ferror(f) || !feof(f)) {
1535 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1540 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1544 // Add new variable if necessary.
1545 if(action > 0 || (action == 0 && !set)) {
1546 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1547 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1554 fprintf(stderr, "No matching configuration variables found.\n");
1558 // Make sure we wrote everything...
1560 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1564 // Could we find what we had to remove?
1565 if(action < 0 && !removed) {
1567 fprintf(stderr, "No configuration variables deleted.\n");
1571 // Replace the configuration file with the new one
1573 if(remove(filename)) {
1574 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1578 if(rename(tmpfile, filename)) {
1579 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1583 // Silently try notifying a running tincd of changes.
1584 if(connect_tincd(false))
1585 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1590 bool check_id(const char *name) {
1594 for(int i = 0; i < strlen(name); i++) {
1595 if(!isalnum(name[i]) && name[i] != '_')
1602 static int cmd_init(int argc, char *argv[]) {
1603 if(!access(tinc_conf, F_OK)) {
1604 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1609 fprintf(stderr, "Too many arguments!\n");
1611 } else if(argc < 2) {
1614 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1616 if(!fgets(buf, sizeof buf, stdin)) {
1617 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1620 int len = rstrip(buf);
1622 fprintf(stderr, "No name given!\n");
1627 fprintf(stderr, "No Name given!\n");
1631 name = strdup(argv[1]);
1633 fprintf(stderr, "No Name given!\n");
1638 if(!check_id(name)) {
1639 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1643 if(mkdir(confdir, 0755) && errno != EEXIST) {
1644 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1648 if(mkdir(confbase, 0755) && errno != EEXIST) {
1649 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1653 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1654 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1658 FILE *f = fopen(tinc_conf, "w");
1660 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1664 fprintf(f, "Name = %s\n", name);
1667 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1672 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1673 if(access(filename, F_OK)) {
1674 FILE *f = fopen(filename, "w");
1676 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1679 fchmod(fileno(f), 0755);
1680 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");
1689 static int cmd_generate_keys(int argc, char *argv[]) {
1691 fprintf(stderr, "Too many arguments!\n");
1695 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1698 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1700 fprintf(stderr, "Too many arguments!\n");
1704 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1707 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1709 fprintf(stderr, "Too many arguments!\n");
1713 return !ecdsa_keygen(true);
1716 static int cmd_help(int argc, char *argv[]) {
1721 static int cmd_version(int argc, char *argv[]) {
1723 fprintf(stderr, "Too many arguments!\n");
1731 static int cmd_info(int argc, char *argv[]) {
1733 fprintf(stderr, "Invalid number of arguments.\n");
1737 if(!connect_tincd(true))
1740 return info(fd, argv[1]);
1743 static const char *conffiles[] = {
1754 static int cmd_edit(int argc, char *argv[]) {
1756 fprintf(stderr, "Invalid number of arguments.\n");
1760 char *filename = NULL;
1762 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1763 for(int i = 0; conffiles[i]; i++) {
1764 if(!strcmp(argv[1], conffiles[i])) {
1765 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1774 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1775 char *dash = strchr(argv[1], '-');
1778 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1779 fprintf(stderr, "Invalid configuration filename.\n");
1787 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1789 xasprintf(&command, "edit \"%s\"", filename);
1791 int result = system(command);
1795 // Silently try notifying a running tincd of changes.
1796 if(connect_tincd(false))
1797 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1802 static int export(const char *name, FILE *out) {
1804 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1805 FILE *in = fopen(filename, "r");
1807 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1811 fprintf(out, "Name = %s\n", name);
1813 while(fgets(buf, sizeof buf, in)) {
1814 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1819 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1828 static int cmd_export(int argc, char *argv[]) {
1830 fprintf(stderr, "Too many arguments!\n");
1834 char *name = get_my_name();
1838 int result = export(name, stdout);
1846 static int cmd_export_all(int argc, char *argv[]) {
1848 fprintf(stderr, "Too many arguments!\n");
1852 DIR *dir = opendir(hosts_dir);
1854 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1862 while((ent = readdir(dir))) {
1863 if(!check_id(ent->d_name))
1869 printf("#---------------------------------------------------------------#\n");
1871 result |= export(ent->d_name, stdout);
1880 static int cmd_import(int argc, char *argv[]) {
1882 fprintf(stderr, "Too many arguments!\n");
1891 char *filename = NULL;
1893 bool firstline = true;
1895 while(fgets(buf, sizeof buf, in)) {
1896 if(sscanf(buf, "Name = %s", name) == 1) {
1899 if(!check_id(name)) {
1900 fprintf(stderr, "Invalid Name in input!\n");
1908 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1910 if(!force && !access(filename, F_OK)) {
1911 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1916 out = fopen(filename, "w");
1918 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1924 } else if(firstline) {
1925 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1930 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1934 if(fputs(buf, out) < 0) {
1935 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1945 fprintf(stderr, "Imported %d host configuration files.\n", count);
1948 fprintf(stderr, "No host configuration files imported.\n");
1953 static int cmd_exchange(int argc, char *argv[]) {
1954 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1957 static int cmd_exchange_all(int argc, char *argv[]) {
1958 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1961 static const struct {
1962 const char *command;
1963 int (*function)(int argc, char *argv[]);
1965 {"start", cmd_start},
1967 {"restart", cmd_restart},
1968 {"reload", cmd_reload},
1970 {"purge", cmd_purge},
1971 {"debug", cmd_debug},
1972 {"retry", cmd_retry},
1973 {"connect", cmd_connect},
1974 {"disconnect", cmd_disconnect},
1979 {"config", cmd_config},
1981 {"generate-keys", cmd_generate_keys},
1982 {"generate-rsa-keys", cmd_generate_rsa_keys},
1983 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1985 {"version", cmd_version},
1988 {"export", cmd_export},
1989 {"export-all", cmd_export_all},
1990 {"import", cmd_import},
1991 {"exchange", cmd_exchange},
1992 {"exchange-all", cmd_exchange_all},
1996 #ifdef HAVE_READLINE
1997 static char *complete_command(const char *text, int state) {
2005 while(commands[i].command) {
2006 if(!strncasecmp(commands[i].command, text, strlen(text)))
2007 return xstrdup(commands[i].command);
2014 static char *complete_dump(const char *text, int state) {
2015 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2024 if(!strncasecmp(matches[i], text, strlen(text)))
2025 return xstrdup(matches[i]);
2032 static char *complete_config(const char *text, int state) {
2033 const char *sub[] = {"get", "set", "add", "del"};
2037 if(!strchr(rl_line_buffer + 7, ' '))
2041 for(int i = 0; i < 4; i++) {
2042 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2054 while(i < 0 || variables[i].name) {
2055 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2056 return xstrdup(sub[i + 4]);
2058 char *dot = strchr(text, '.');
2060 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2062 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2066 if(!strncasecmp(variables[i].name, text, strlen(text)))
2067 return xstrdup(variables[i].name);
2076 static char *complete_info(const char *text, int state) {
2080 if(!connect_tincd(false))
2082 // Check the list of nodes
2083 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2084 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2087 while(recvline(fd, line, sizeof line)) {
2089 int n = sscanf(line, "%d %d %s", &code, &req, item);
2099 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2103 if(!strncmp(item, text, strlen(text)))
2104 return xstrdup(strip_weight(item));
2110 static char *complete_nothing(const char *text, int state) {
2114 static char **completion (const char *text, int start, int end) {
2115 char **matches = NULL;
2118 matches = rl_completion_matches(text, complete_command);
2119 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2120 matches = rl_completion_matches(text, complete_dump);
2121 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2122 matches = rl_completion_matches(text, complete_config);
2123 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2124 matches = rl_completion_matches(text, complete_info);
2130 static int cmd_shell(int argc, char *argv[]) {
2132 xasprintf(&prompt, "%s> ", identname);
2136 int maxargs = argc + 16;
2137 char **nargv = xmalloc(maxargs * sizeof *nargv);
2139 for(int i = 0; i < argc; i++)
2142 #ifdef HAVE_READLINE
2143 rl_readline_name = "tinc";
2144 rl_completion_entry_function = complete_nothing;
2145 rl_attempted_completion_function = completion;
2146 rl_filename_completion_desired = 0;
2151 #ifdef HAVE_READLINE
2155 rl_basic_word_break_characters = "\t\n ";
2156 line = readline(prompt);
2158 copy = xstrdup(line);
2160 line = fgets(buf, sizeof buf, stdin);
2164 fputs(prompt, stdout);
2166 line = fgets(buf, sizeof buf, stdin);
2172 /* Ignore comments */
2180 char *p = line + strspn(line, " \t\n");
2181 char *next = strtok(p, " \t\n");
2184 if(nargc >= maxargs) {
2185 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2188 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2193 next = strtok(NULL, " \t\n");
2199 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2204 for(int i = 0; commands[i].command; i++) {
2205 if(!strcasecmp(nargv[argc], commands[i].command)) {
2206 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2212 #ifdef HAVE_READLINE
2218 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2231 int main(int argc, char *argv[]) {
2232 program_name = argv[0];
2236 if(!parse_options(argc, argv))
2240 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2241 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2253 tty = isatty(0) && isatty(1);
2256 return cmd_shell(argc, argv);
2258 for(int i = 0; commands[i].command; i++) {
2259 if(!strcasecmp(argv[optind], commands[i].command))
2260 return commands[i].function(argc - optind, argv + optind);
2263 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);