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(!(key = ecdsa_generate())) {
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 if(!ecdsa_write_pem_private_key(key, f)) {
374 fprintf(stderr, "Error writing private key!\n");
383 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
385 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
387 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
393 char *pubkey = ecdsa_get_base64_public_key(key);
394 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
404 Generate a public/private RSA keypair, and ask for a file to store
407 static bool rsa_keygen(int bits, bool ask) {
410 char *pubname, *privname;
412 fprintf(stderr, "Generating %d bits keys:\n", bits);
414 if(!(key = rsa_generate(bits, 0x10001))) {
415 fprintf(stderr, "Error during key generation!\n");
418 fprintf(stderr, "Done.\n");
420 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
421 f = ask_and_open(privname, "private RSA key", "a", ask);
428 /* Make it unreadable for others. */
429 fchmod(fileno(f), 0600);
432 if(!rsa_write_pem_private_key(key, f)) {
433 fprintf(stderr, "Error writing private key!\n");
442 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
444 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
446 f = ask_and_open(pubname, "public RSA key", "a", ask);
452 if(!rsa_write_pem_public_key(key, f)) {
453 fprintf(stderr, "Error writing public key!\n");
465 static char buffer[4096];
466 static size_t blen = 0;
468 bool recvline(int fd, char *line, size_t len) {
469 char *newline = NULL;
471 while(!(newline = memchr(buffer, '\n', blen))) {
472 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
473 if(result == -1 && errno == EINTR)
480 if(newline - buffer >= len)
483 len = newline - buffer;
485 memcpy(line, buffer, len);
487 memmove(buffer, newline + 1, blen - len - 1);
493 static bool recvdata(int fd, char *data, size_t len) {
495 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
496 if(result == -1 && errno == EINTR)
503 memcpy(data, buffer, len);
504 memmove(buffer, buffer + len, blen - len);
510 bool sendline(int fd, char *format, ...) {
511 static char buffer[4096];
516 va_start(ap, format);
517 blen = vsnprintf(buffer, sizeof buffer, format, ap);
520 if(blen < 1 || blen >= sizeof buffer)
527 int result = send(fd, p, blen, 0);
528 if(result == -1 && errno == EINTR)
539 static void pcap(int fd, FILE *out, int snaplen) {
540 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
548 uint32_t tz_accuracy;
555 snaplen ?: sizeof data,
568 fwrite(&header, sizeof header, 1, out);
572 while(recvline(fd, line, sizeof line)) {
574 int n = sscanf(line, "%d %d %d", &code, &req, &len);
575 gettimeofday(&tv, NULL);
576 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
578 if(!recvdata(fd, data, len))
580 packet.tv_sec = tv.tv_sec;
581 packet.tv_usec = tv.tv_usec;
583 packet.origlen = len;
584 fwrite(&packet, sizeof packet, 1, out);
585 fwrite(data, len, 1, out);
590 static void logcontrol(int fd, FILE *out, int level) {
591 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
595 while(recvline(fd, line, sizeof line)) {
597 int n = sscanf(line, "%d %d %d", &code, &req, &len);
598 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
600 if(!recvdata(fd, data, len))
602 fwrite(data, len, 1, out);
609 static bool remove_service(void) {
610 SC_HANDLE manager = NULL;
611 SC_HANDLE service = NULL;
612 SERVICE_STATUS status = {0};
614 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
616 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
620 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
623 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
627 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
628 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
630 fprintf(stderr, "%s service stopped\n", identname);
632 if(!DeleteService(service)) {
633 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
637 fprintf(stderr, "%s service removed\n", identname);
643 static bool connect_tincd(bool verbose) {
648 struct timeval tv = {0, 0};
649 if(select(fd + 1, &r, NULL, NULL, &tv)) {
650 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
658 FILE *f = fopen(pidfilename, "r");
661 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
668 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
670 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
678 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
680 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
686 struct sockaddr_un sa;
687 sa.sun_family = AF_UNIX;
688 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
690 fd = socket(AF_UNIX, SOCK_STREAM, 0);
693 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
697 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
699 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
705 struct addrinfo hints = {
706 .ai_family = AF_UNSPEC,
707 .ai_socktype = SOCK_STREAM,
708 .ai_protocol = IPPROTO_TCP,
712 struct addrinfo *res = NULL;
714 if(getaddrinfo(host, port, &hints, &res) || !res) {
716 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
720 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
723 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
728 unsigned long arg = 0;
730 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
732 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
736 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
738 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
750 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
752 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
758 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
760 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
762 fprintf(stderr, "Could not fully establish control socket connection\n");
772 static int cmd_start(int argc, char *argv[]) {
773 if(connect_tincd(false)) {
775 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
777 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
782 char *slash = strrchr(program_name, '/');
785 if ((c = strrchr(program_name, '\\')) > slash)
790 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
795 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
798 for(int i = 1; i < optind; i++)
799 nargv[nargc++] = orig_argv[i];
800 for(int i = 1; i < argc; i++)
801 nargv[nargc++] = argv[i];
805 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
810 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
816 exit(execvp(c, nargv));
821 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
822 fprintf(stderr, "Error starting %s\n", c);
830 static int cmd_stop(int argc, char *argv[]) {
832 fprintf(stderr, "Too many arguments!\n");
837 if(!connect_tincd(true)) {
839 if(kill(pid, SIGTERM)) {
840 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
844 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
845 waitpid(pid, NULL, 0);
852 sendline(fd, "%d %d", CONTROL, REQ_STOP);
854 while(recvline(fd, line, sizeof line)) {
855 // Wait for tincd to close the connection...
858 if(!remove_service())
868 static int cmd_restart(int argc, char *argv[]) {
869 cmd_stop(argc, argv);
870 return cmd_start(argc, argv);
873 static int cmd_reload(int argc, char *argv[]) {
875 fprintf(stderr, "Too many arguments!\n");
879 if(!connect_tincd(true))
882 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
883 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
884 fprintf(stderr, "Could not reload configuration.\n");
892 static int cmd_dump(int argc, char *argv[]) {
893 bool only_reachable = false;
895 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
896 if(strcasecmp(argv[2], "nodes")) {
897 fprintf(stderr, "`reachable' only supported for nodes.\n");
901 only_reachable = true;
907 fprintf(stderr, "Invalid number of arguments.\n");
912 if(!connect_tincd(true))
917 if(!strcasecmp(argv[1], "nodes"))
918 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
919 else if(!strcasecmp(argv[1], "edges"))
920 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
921 else if(!strcasecmp(argv[1], "subnets"))
922 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
923 else if(!strcasecmp(argv[1], "connections"))
924 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
925 else if(!strcasecmp(argv[1], "graph")) {
926 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
927 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
929 } else if(!strcasecmp(argv[1], "digraph")) {
930 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
931 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
934 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
941 else if(do_graph == 2)
942 printf("digraph {\n");
944 while(recvline(fd, line, sizeof line)) {
945 char node1[4096], node2[4096];
946 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
948 if(do_graph && req == REQ_DUMP_NODES)
967 int cipher, digest, maclength, compression, distance, socket, weight;
968 short int pmtu, minmtu, maxmtu;
969 unsigned int options, status_int;
970 node_status_t status;
971 long int last_state_change;
974 case REQ_DUMP_NODES: {
975 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);
977 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
981 memcpy(&status, &status_int, sizeof status);
984 const char *color = "black";
985 if(!strcmp(host, "MYSELF"))
987 else if(!status.reachable)
989 else if(strcmp(via, node))
991 else if(!status.validkey)
995 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
997 if(only_reachable && !status.reachable)
999 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",
1000 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1004 case REQ_DUMP_EDGES: {
1005 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1007 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1012 float w = 1 + 65536.0 / weight;
1013 if(do_graph == 1 && strcmp(node1, node2) > 0)
1014 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1015 else if(do_graph == 2)
1016 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1018 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1022 case REQ_DUMP_SUBNETS: {
1023 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1025 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1028 printf("%s owner %s\n", strip_weight(subnet), node);
1031 case REQ_DUMP_CONNECTIONS: {
1032 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1034 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1037 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1041 fprintf(stderr, "Unable to parse dump from tincd.\n");
1046 fprintf(stderr, "Error receiving dump.\n");
1050 static int cmd_purge(int argc, char *argv[]) {
1052 fprintf(stderr, "Too many arguments!\n");
1056 if(!connect_tincd(true))
1059 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1060 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1061 fprintf(stderr, "Could not purge old information.\n");
1068 static int cmd_debug(int argc, char *argv[]) {
1070 fprintf(stderr, "Invalid number of arguments.\n");
1074 if(!connect_tincd(true))
1077 int debuglevel = atoi(argv[1]);
1080 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1081 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1082 fprintf(stderr, "Could not set debug level.\n");
1086 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1090 static int cmd_retry(int argc, char *argv[]) {
1092 fprintf(stderr, "Too many arguments!\n");
1096 if(!connect_tincd(true))
1099 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1100 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1101 fprintf(stderr, "Could not retry outgoing connections.\n");
1108 static int cmd_connect(int argc, char *argv[]) {
1110 fprintf(stderr, "Invalid number of arguments.\n");
1114 if(!check_id(argv[1])) {
1115 fprintf(stderr, "Invalid name for node.\n");
1119 if(!connect_tincd(true))
1122 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1123 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1124 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1131 static int cmd_disconnect(int argc, char *argv[]) {
1133 fprintf(stderr, "Invalid number of arguments.\n");
1137 if(!check_id(argv[1])) {
1138 fprintf(stderr, "Invalid name for node.\n");
1142 if(!connect_tincd(true))
1145 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1146 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1147 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1154 static int cmd_top(int argc, char *argv[]) {
1156 fprintf(stderr, "Too many arguments!\n");
1161 if(!connect_tincd(true))
1167 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1172 static int cmd_pcap(int argc, char *argv[]) {
1174 fprintf(stderr, "Too many arguments!\n");
1178 if(!connect_tincd(true))
1181 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1185 static int cmd_log(int argc, char *argv[]) {
1187 fprintf(stderr, "Too many arguments!\n");
1191 if(!connect_tincd(true))
1194 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1198 static int cmd_pid(int argc, char *argv[]) {
1200 fprintf(stderr, "Too many arguments!\n");
1204 if(!connect_tincd(true) && !pid)
1207 printf("%d\n", pid);
1211 static int rstrip(char *value) {
1212 int len = strlen(value);
1213 while(len && strchr("\t\r\n ", value[len - 1]))
1218 static char *get_my_name(bool verbose) {
1219 FILE *f = fopen(tinc_conf, "r");
1222 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1228 while(fgets(buf, sizeof buf, f)) {
1229 int len = strcspn(buf, "\t =");
1231 value += strspn(value, "\t ");
1234 value += strspn(value, "\t ");
1239 if(strcasecmp(buf, "Name"))
1243 return strdup(value);
1249 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1253 #define VAR_SERVER 1 /* Should be in tinc.conf */
1254 #define VAR_HOST 2 /* Can be in host config file */
1255 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1256 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1261 } const variables[] = {
1262 /* Server configuration */
1263 {"AddressFamily", VAR_SERVER},
1264 {"AutoConnect", VAR_SERVER},
1265 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1266 {"BindToInterface", VAR_SERVER},
1267 {"Broadcast", VAR_SERVER},
1268 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1269 {"DecrementTTL", VAR_SERVER},
1270 {"Device", VAR_SERVER},
1271 {"DeviceType", VAR_SERVER},
1272 {"DirectOnly", VAR_SERVER},
1273 {"ECDSAPrivateKeyFile", VAR_SERVER},
1274 {"ExperimentalProtocol", VAR_SERVER},
1275 {"Forwarding", VAR_SERVER},
1276 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1277 {"Hostnames", VAR_SERVER},
1278 {"IffOneQueue", VAR_SERVER},
1279 {"Interface", VAR_SERVER},
1280 {"KeyExpire", VAR_SERVER},
1281 {"LocalDiscovery", VAR_SERVER},
1282 {"MACExpire", VAR_SERVER},
1283 {"MaxOutputBufferSize", VAR_SERVER},
1284 {"MaxTimeout", VAR_SERVER},
1285 {"Mode", VAR_SERVER},
1286 {"Name", VAR_SERVER},
1287 {"PingInterval", VAR_SERVER},
1288 {"PingTimeout", VAR_SERVER},
1289 {"PriorityInheritance", VAR_SERVER},
1290 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1291 {"PrivateKeyFile", VAR_SERVER},
1292 {"ProcessPriority", VAR_SERVER},
1293 {"Proxy", VAR_SERVER},
1294 {"ReplayWindow", VAR_SERVER},
1295 {"ScriptsExtension", VAR_SERVER},
1296 {"ScriptsInterpreter", VAR_SERVER},
1297 {"StrictSubnets", VAR_SERVER},
1298 {"TunnelServer", VAR_SERVER},
1299 {"UDPRcvBuf", VAR_SERVER},
1300 {"UDPSndBuf", VAR_SERVER},
1301 {"VDEGroup", VAR_SERVER},
1302 {"VDEPort", VAR_SERVER},
1303 /* Host configuration */
1304 {"Address", VAR_HOST | VAR_MULTIPLE},
1305 {"Cipher", VAR_SERVER | VAR_HOST},
1306 {"ClampMSS", VAR_SERVER | VAR_HOST},
1307 {"Compression", VAR_SERVER | VAR_HOST},
1308 {"Digest", VAR_SERVER | VAR_HOST},
1309 {"ECDSAPublicKey", VAR_HOST},
1310 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1311 {"IndirectData", VAR_SERVER | VAR_HOST},
1312 {"MACLength", VAR_SERVER | VAR_HOST},
1313 {"PMTU", VAR_SERVER | VAR_HOST},
1314 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1316 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1317 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1318 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1319 {"TCPOnly", VAR_SERVER | VAR_HOST},
1320 {"Weight", VAR_HOST},
1324 static int cmd_config(int argc, char *argv[]) {
1326 fprintf(stderr, "Invalid number of arguments.\n");
1330 if(strcasecmp(argv[0], "config"))
1334 if(!strcasecmp(argv[1], "get")) {
1336 } else if(!strcasecmp(argv[1], "add")) {
1337 argv++, argc--, action = 1;
1338 } else if(!strcasecmp(argv[1], "del")) {
1339 argv++, argc--, action = -1;
1340 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1341 argv++, argc--, action = 0;
1345 fprintf(stderr, "Invalid number of arguments.\n");
1349 // Concatenate the rest of the command line
1350 strncpy(line, argv[1], sizeof line - 1);
1351 for(int i = 2; i < argc; i++) {
1352 strncat(line, " ", sizeof line - 1 - strlen(line));
1353 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1356 // Liberal parsing into node name, variable name and value.
1362 len = strcspn(line, "\t =");
1364 value += strspn(value, "\t ");
1367 value += strspn(value, "\t ");
1370 variable = strchr(line, '.');
1379 fprintf(stderr, "No variable given.\n");
1383 if(action >= 0 && !*value) {
1384 fprintf(stderr, "No value for variable given.\n");
1388 if(action < -1 && *value)
1391 /* Some simple checks. */
1394 for(int i = 0; variables[i].name; i++) {
1395 if(strcasecmp(variables[i].name, variable))
1399 variable = (char *)variables[i].name;
1401 /* Discourage use of obsolete variables. */
1403 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1405 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1407 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1412 /* Don't put server variables in host config files */
1414 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1416 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1418 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1423 /* Should this go into our own host config file? */
1425 if(!node && !(variables[i].type & VAR_SERVER)) {
1426 node = get_my_name(true);
1434 if(node && !check_id(node)) {
1435 fprintf(stderr, "Invalid name for node.\n");
1440 if(force || action < 0) {
1441 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1443 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1448 // Open the right configuration file.
1451 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1453 filename = tinc_conf;
1455 FILE *f = fopen(filename, "r");
1457 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1461 char *tmpfile = NULL;
1465 xasprintf(&tmpfile, "%s.config.tmp", filename);
1466 tf = fopen(tmpfile, "w");
1468 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1474 // Copy the file, making modifications on the fly, unless we are just getting a value.
1478 bool removed = false;
1481 while(fgets(buf1, sizeof buf1, f)) {
1482 buf1[sizeof buf1 - 1] = 0;
1483 strncpy(buf2, buf1, sizeof buf2);
1485 // Parse line in a simple way
1489 len = strcspn(buf2, "\t =");
1490 bvalue = buf2 + len;
1491 bvalue += strspn(bvalue, "\t ");
1492 if(*bvalue == '=') {
1494 bvalue += strspn(bvalue, "\t ");
1500 if(!strcasecmp(buf2, variable)) {
1504 printf("%s\n", bvalue);
1506 } else if(action == -1) {
1507 if(!*value || !strcasecmp(bvalue, value)) {
1512 } else if(action == 0) {
1513 // Already set? Delete the rest...
1516 // Otherwise, replace.
1517 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1518 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1527 // Copy original line...
1528 if(fputs(buf1, tf) < 0) {
1529 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1533 // Add newline if it is missing...
1534 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1535 if(fputc('\n', tf) < 0) {
1536 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1543 // Make sure we read everything...
1544 if(ferror(f) || !feof(f)) {
1545 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1550 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1554 // Add new variable if necessary.
1555 if(action > 0 || (action == 0 && !set)) {
1556 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1557 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1564 fprintf(stderr, "No matching configuration variables found.\n");
1568 // Make sure we wrote everything...
1570 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1574 // Could we find what we had to remove?
1575 if(action < 0 && !removed) {
1577 fprintf(stderr, "No configuration variables deleted.\n");
1581 // Replace the configuration file with the new one
1583 if(remove(filename)) {
1584 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1588 if(rename(tmpfile, filename)) {
1589 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1593 // Silently try notifying a running tincd of changes.
1594 if(connect_tincd(false))
1595 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1600 bool check_id(const char *name) {
1604 for(int i = 0; i < strlen(name); i++) {
1605 if(!isalnum(name[i]) && name[i] != '_')
1612 static int cmd_init(int argc, char *argv[]) {
1613 if(!access(tinc_conf, F_OK)) {
1614 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1619 fprintf(stderr, "Too many arguments!\n");
1621 } else if(argc < 2) {
1624 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1626 if(!fgets(buf, sizeof buf, stdin)) {
1627 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1630 int len = rstrip(buf);
1632 fprintf(stderr, "No name given!\n");
1637 fprintf(stderr, "No Name given!\n");
1641 name = strdup(argv[1]);
1643 fprintf(stderr, "No Name given!\n");
1648 if(!check_id(name)) {
1649 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1653 if(mkdir(confdir, 0755) && errno != EEXIST) {
1654 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1658 if(mkdir(confbase, 0755) && errno != EEXIST) {
1659 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1663 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1664 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1668 FILE *f = fopen(tinc_conf, "w");
1670 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1674 fprintf(f, "Name = %s\n", name);
1677 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1682 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1683 if(access(filename, F_OK)) {
1684 FILE *f = fopen(filename, "w");
1686 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1689 fchmod(fileno(f), 0755);
1690 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");
1699 static int cmd_generate_keys(int argc, char *argv[]) {
1701 fprintf(stderr, "Too many arguments!\n");
1706 name = get_my_name(false);
1708 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1711 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1713 fprintf(stderr, "Too many arguments!\n");
1718 name = get_my_name(false);
1720 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1723 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1725 fprintf(stderr, "Too many arguments!\n");
1730 name = get_my_name(false);
1732 return !ecdsa_keygen(true);
1735 static int cmd_help(int argc, char *argv[]) {
1740 static int cmd_version(int argc, char *argv[]) {
1742 fprintf(stderr, "Too many arguments!\n");
1750 static int cmd_info(int argc, char *argv[]) {
1752 fprintf(stderr, "Invalid number of arguments.\n");
1756 if(!connect_tincd(true))
1759 return info(fd, argv[1]);
1762 static const char *conffiles[] = {
1773 static int cmd_edit(int argc, char *argv[]) {
1775 fprintf(stderr, "Invalid number of arguments.\n");
1779 char *filename = NULL;
1781 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1782 for(int i = 0; conffiles[i]; i++) {
1783 if(!strcmp(argv[1], conffiles[i])) {
1784 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1793 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1794 char *dash = strchr(argv[1], '-');
1797 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1798 fprintf(stderr, "Invalid configuration filename.\n");
1806 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1808 xasprintf(&command, "edit \"%s\"", filename);
1810 int result = system(command);
1814 // Silently try notifying a running tincd of changes.
1815 if(connect_tincd(false))
1816 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1821 static int export(const char *name, FILE *out) {
1823 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1824 FILE *in = fopen(filename, "r");
1826 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1830 fprintf(out, "Name = %s\n", name);
1832 while(fgets(buf, sizeof buf, in)) {
1833 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1838 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1847 static int cmd_export(int argc, char *argv[]) {
1849 fprintf(stderr, "Too many arguments!\n");
1853 char *name = get_my_name(true);
1857 int result = export(name, stdout);
1865 static int cmd_export_all(int argc, char *argv[]) {
1867 fprintf(stderr, "Too many arguments!\n");
1871 DIR *dir = opendir(hosts_dir);
1873 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1881 while((ent = readdir(dir))) {
1882 if(!check_id(ent->d_name))
1888 printf("#---------------------------------------------------------------#\n");
1890 result |= export(ent->d_name, stdout);
1899 static int cmd_import(int argc, char *argv[]) {
1901 fprintf(stderr, "Too many arguments!\n");
1910 char *filename = NULL;
1912 bool firstline = true;
1914 while(fgets(buf, sizeof buf, in)) {
1915 if(sscanf(buf, "Name = %s", name) == 1) {
1918 if(!check_id(name)) {
1919 fprintf(stderr, "Invalid Name in input!\n");
1927 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1929 if(!force && !access(filename, F_OK)) {
1930 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1935 out = fopen(filename, "w");
1937 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1943 } else if(firstline) {
1944 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1949 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1953 if(fputs(buf, out) < 0) {
1954 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1964 fprintf(stderr, "Imported %d host configuration files.\n", count);
1967 fprintf(stderr, "No host configuration files imported.\n");
1972 static int cmd_exchange(int argc, char *argv[]) {
1973 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1976 static int cmd_exchange_all(int argc, char *argv[]) {
1977 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1980 static const struct {
1981 const char *command;
1982 int (*function)(int argc, char *argv[]);
1985 {"start", cmd_start},
1987 {"restart", cmd_restart},
1988 {"reload", cmd_reload},
1990 {"purge", cmd_purge},
1991 {"debug", cmd_debug},
1992 {"retry", cmd_retry},
1993 {"connect", cmd_connect},
1994 {"disconnect", cmd_disconnect},
1999 {"config", cmd_config, true},
2000 {"add", cmd_config},
2001 {"del", cmd_config},
2002 {"get", cmd_config},
2003 {"set", cmd_config},
2005 {"generate-keys", cmd_generate_keys},
2006 {"generate-rsa-keys", cmd_generate_rsa_keys},
2007 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2009 {"version", cmd_version},
2012 {"export", cmd_export},
2013 {"export-all", cmd_export_all},
2014 {"import", cmd_import},
2015 {"exchange", cmd_exchange},
2016 {"exchange-all", cmd_exchange_all},
2020 #ifdef HAVE_READLINE
2021 static char *complete_command(const char *text, int state) {
2029 while(commands[i].command) {
2030 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2031 return xstrdup(commands[i].command);
2038 static char *complete_dump(const char *text, int state) {
2039 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2048 if(!strncasecmp(matches[i], text, strlen(text)))
2049 return xstrdup(matches[i]);
2056 static char *complete_config(const char *text, int state) {
2064 while(variables[i].name) {
2065 char *dot = strchr(text, '.');
2067 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2069 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2073 if(!strncasecmp(variables[i].name, text, strlen(text)))
2074 return xstrdup(variables[i].name);
2082 static char *complete_info(const char *text, int state) {
2086 if(!connect_tincd(false))
2088 // Check the list of nodes
2089 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2090 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2093 while(recvline(fd, line, sizeof line)) {
2095 int n = sscanf(line, "%d %d %s", &code, &req, item);
2105 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2109 if(!strncmp(item, text, strlen(text)))
2110 return xstrdup(strip_weight(item));
2116 static char *complete_nothing(const char *text, int state) {
2120 static char **completion (const char *text, int start, int end) {
2121 char **matches = NULL;
2124 matches = rl_completion_matches(text, complete_command);
2125 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2126 matches = rl_completion_matches(text, complete_dump);
2127 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2128 matches = rl_completion_matches(text, complete_config);
2129 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2130 matches = rl_completion_matches(text, complete_config);
2131 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2132 matches = rl_completion_matches(text, complete_config);
2133 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2134 matches = rl_completion_matches(text, complete_config);
2135 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2136 matches = rl_completion_matches(text, complete_info);
2142 static int cmd_shell(int argc, char *argv[]) {
2144 xasprintf(&prompt, "%s> ", identname);
2148 int maxargs = argc + 16;
2149 char **nargv = xmalloc(maxargs * sizeof *nargv);
2151 for(int i = 0; i < argc; i++)
2154 #ifdef HAVE_READLINE
2155 rl_readline_name = "tinc";
2156 rl_completion_entry_function = complete_nothing;
2157 rl_attempted_completion_function = completion;
2158 rl_filename_completion_desired = 0;
2163 #ifdef HAVE_READLINE
2167 rl_basic_word_break_characters = "\t\n ";
2168 line = readline(prompt);
2170 copy = xstrdup(line);
2172 line = fgets(buf, sizeof buf, stdin);
2176 fputs(prompt, stdout);
2178 line = fgets(buf, sizeof buf, stdin);
2184 /* Ignore comments */
2192 char *p = line + strspn(line, " \t\n");
2193 char *next = strtok(p, " \t\n");
2196 if(nargc >= maxargs) {
2197 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2200 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2205 next = strtok(NULL, " \t\n");
2211 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2216 for(int i = 0; commands[i].command; i++) {
2217 if(!strcasecmp(nargv[argc], commands[i].command)) {
2218 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2224 #ifdef HAVE_READLINE
2230 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2243 int main(int argc, char *argv[]) {
2244 program_name = argv[0];
2248 if(!parse_options(argc, argv))
2252 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2253 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2265 tty = isatty(0) && isatty(1);
2268 return cmd_shell(argc, argv);
2270 for(int i = 0; commands[i].command; i++) {
2271 if(!strcasecmp(argv[optind], commands[i].command))
2272 return commands[i].function(argc - optind, argv + optind);
2275 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);