2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2012 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "readline/readline.h"
26 #include "readline/history.h"
31 #include "control_common.h"
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()));
669 struct addrinfo hints = {
670 .ai_family = AF_UNSPEC,
671 .ai_socktype = SOCK_STREAM,
672 .ai_protocol = IPPROTO_TCP,
676 struct addrinfo *res = NULL;
678 if(getaddrinfo(host, port, &hints, &res) || !res) {
680 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
684 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
687 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
692 unsigned long arg = 0;
694 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
696 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
700 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
702 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
713 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
715 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
721 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
723 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
725 fprintf(stderr, "Could not fully establish control socket connection\n");
735 static int cmd_start(int argc, char *argv[]) {
736 if(connect_tincd(false)) {
738 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
740 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
745 char *slash = strrchr(program_name, '/');
748 if ((c = strrchr(program_name, '\\')) > slash)
753 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
758 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
761 for(int i = 1; i < optind; i++)
762 nargv[nargc++] = orig_argv[i];
763 for(int i = 1; i < argc; i++)
764 nargv[nargc++] = argv[i];
768 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
773 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
779 exit(execvp(c, nargv));
784 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
785 fprintf(stderr, "Error starting %s\n", c);
793 static int cmd_stop(int argc, char *argv[]) {
795 fprintf(stderr, "Too many arguments!\n");
800 if(!connect_tincd(true)) {
802 if(kill(pid, SIGTERM)) {
803 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
807 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
808 waitpid(pid, NULL, 0);
815 sendline(fd, "%d %d", CONTROL, REQ_STOP);
816 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
817 fprintf(stderr, "Could not stop tinc daemon.\n");
821 // Wait for tincd to close the connection...
825 select(fd + 1, &r, NULL, NULL, NULL);
827 if(!remove_service())
837 static int cmd_restart(int argc, char *argv[]) {
838 cmd_stop(argc, argv);
839 return cmd_start(argc, argv);
842 static int cmd_reload(int argc, char *argv[]) {
844 fprintf(stderr, "Too many arguments!\n");
848 if(!connect_tincd(true))
851 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
852 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
853 fprintf(stderr, "Could not reload configuration.\n");
861 static int cmd_dump(int argc, char *argv[]) {
862 bool only_reachable = false;
864 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
865 if(strcasecmp(argv[2], "nodes")) {
866 fprintf(stderr, "`reachable' only supported for nodes.\n");
870 only_reachable = true;
876 fprintf(stderr, "Invalid number of arguments.\n");
881 if(!connect_tincd(true))
886 if(!strcasecmp(argv[1], "nodes"))
887 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
888 else if(!strcasecmp(argv[1], "edges"))
889 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
890 else if(!strcasecmp(argv[1], "subnets"))
891 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
892 else if(!strcasecmp(argv[1], "connections"))
893 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
894 else if(!strcasecmp(argv[1], "graph")) {
895 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
896 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
898 } else if(!strcasecmp(argv[1], "digraph")) {
899 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
900 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
903 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
910 else if(do_graph == 2)
911 printf("digraph {\n");
913 while(recvline(fd, line, sizeof line)) {
914 char node1[4096], node2[4096];
915 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
917 if(do_graph && req == REQ_DUMP_NODES)
936 int cipher, digest, maclength, compression, distance, socket, weight;
937 short int pmtu, minmtu, maxmtu;
938 unsigned int options, status_int;
939 node_status_t status;
940 long int last_state_change;
943 case REQ_DUMP_NODES: {
944 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);
946 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
950 memcpy(&status, &status_int, sizeof status);
953 const char *color = "black";
954 if(!strcmp(host, "MYSELF"))
956 else if(!status.reachable)
958 else if(strcmp(via, node))
960 else if(!status.validkey)
964 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
966 if(only_reachable && !status.reachable)
968 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",
969 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
973 case REQ_DUMP_EDGES: {
974 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
976 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
981 float w = 1 + 65536.0 / weight;
982 if(do_graph == 1 && strcmp(node1, node2) > 0)
983 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
984 else if(do_graph == 2)
985 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
987 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
991 case REQ_DUMP_SUBNETS: {
992 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
994 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
997 printf("%s owner %s\n", strip_weight(subnet), node);
1000 case REQ_DUMP_CONNECTIONS: {
1001 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1003 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1006 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1010 fprintf(stderr, "Unable to parse dump from tincd.\n");
1015 fprintf(stderr, "Error receiving dump.\n");
1019 static int cmd_purge(int argc, char *argv[]) {
1021 fprintf(stderr, "Too many arguments!\n");
1025 if(!connect_tincd(true))
1028 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1029 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1030 fprintf(stderr, "Could not purge old information.\n");
1037 static int cmd_debug(int argc, char *argv[]) {
1039 fprintf(stderr, "Invalid number of arguments.\n");
1043 if(!connect_tincd(true))
1046 int debuglevel = atoi(argv[1]);
1049 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1050 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1051 fprintf(stderr, "Could not set debug level.\n");
1055 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1059 static int cmd_retry(int argc, char *argv[]) {
1061 fprintf(stderr, "Too many arguments!\n");
1065 if(!connect_tincd(true))
1068 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1069 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1070 fprintf(stderr, "Could not retry outgoing connections.\n");
1077 static int cmd_connect(int argc, char *argv[]) {
1079 fprintf(stderr, "Invalid number of arguments.\n");
1083 if(!check_id(argv[1])) {
1084 fprintf(stderr, "Invalid name for node.\n");
1088 if(!connect_tincd(true))
1091 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1092 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1093 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1100 static int cmd_disconnect(int argc, char *argv[]) {
1102 fprintf(stderr, "Invalid number of arguments.\n");
1106 if(!check_id(argv[1])) {
1107 fprintf(stderr, "Invalid name for node.\n");
1111 if(!connect_tincd(true))
1114 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1115 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1116 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1123 static int cmd_top(int argc, char *argv[]) {
1125 fprintf(stderr, "Too many arguments!\n");
1130 if(!connect_tincd(true))
1136 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1141 static int cmd_pcap(int argc, char *argv[]) {
1143 fprintf(stderr, "Too many arguments!\n");
1147 if(!connect_tincd(true))
1150 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1154 static int cmd_log(int argc, char *argv[]) {
1156 fprintf(stderr, "Too many arguments!\n");
1160 if(!connect_tincd(true))
1163 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1167 static int cmd_pid(int argc, char *argv[]) {
1169 fprintf(stderr, "Too many arguments!\n");
1173 if(!connect_tincd(true) && !pid)
1176 printf("%d\n", pid);
1180 static int rstrip(char *value) {
1181 int len = strlen(value);
1182 while(len && strchr("\t\r\n ", value[len - 1]))
1187 static char *get_my_name() {
1188 FILE *f = fopen(tinc_conf, "r");
1190 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1196 while(fgets(buf, sizeof buf, f)) {
1197 int len = strcspn(buf, "\t =");
1199 value += strspn(value, "\t ");
1202 value += strspn(value, "\t ");
1207 if(strcasecmp(buf, "Name"))
1211 return strdup(value);
1216 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1220 #define VAR_SERVER 1 /* Should be in tinc.conf */
1221 #define VAR_HOST 2 /* Can be in host config file */
1222 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1223 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1228 } const variables[] = {
1229 /* Server configuration */
1230 {"AddressFamily", VAR_SERVER},
1231 {"AutoConnect", VAR_SERVER},
1232 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1233 {"BindToInterface", VAR_SERVER},
1234 {"Broadcast", VAR_SERVER},
1235 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1236 {"DecrementTTL", VAR_SERVER},
1237 {"Device", VAR_SERVER},
1238 {"DeviceType", VAR_SERVER},
1239 {"DirectOnly", VAR_SERVER},
1240 {"ECDSAPrivateKeyFile", VAR_SERVER},
1241 {"ExperimentalProtocol", VAR_SERVER},
1242 {"Forwarding", VAR_SERVER},
1243 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1244 {"Hostnames", VAR_SERVER},
1245 {"IffOneQueue", VAR_SERVER},
1246 {"Interface", VAR_SERVER},
1247 {"KeyExpire", VAR_SERVER},
1248 {"LocalDiscovery", VAR_SERVER},
1249 {"MACExpire", VAR_SERVER},
1250 {"MaxOutputBufferSize", VAR_SERVER},
1251 {"MaxTimeout", VAR_SERVER},
1252 {"Mode", VAR_SERVER},
1253 {"Name", VAR_SERVER},
1254 {"PingInterval", VAR_SERVER},
1255 {"PingTimeout", VAR_SERVER},
1256 {"PriorityInheritance", VAR_SERVER},
1257 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1258 {"PrivateKeyFile", VAR_SERVER},
1259 {"ProcessPriority", VAR_SERVER},
1260 {"Proxy", VAR_SERVER},
1261 {"ReplayWindow", VAR_SERVER},
1262 {"ScriptsExtension", VAR_SERVER},
1263 {"ScriptsInterpreter", VAR_SERVER},
1264 {"StrictSubnets", VAR_SERVER},
1265 {"TunnelServer", VAR_SERVER},
1266 {"UDPRcvBuf", VAR_SERVER},
1267 {"UDPSndBuf", VAR_SERVER},
1268 {"VDEGroup", VAR_SERVER},
1269 {"VDEPort", VAR_SERVER},
1270 /* Host configuration */
1271 {"Address", VAR_HOST | VAR_MULTIPLE},
1272 {"Cipher", VAR_SERVER | VAR_HOST},
1273 {"ClampMSS", VAR_SERVER | VAR_HOST},
1274 {"Compression", VAR_SERVER | VAR_HOST},
1275 {"Digest", VAR_SERVER | VAR_HOST},
1276 {"ECDSAPublicKey", VAR_HOST},
1277 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1278 {"IndirectData", VAR_SERVER | VAR_HOST},
1279 {"MACLength", VAR_SERVER | VAR_HOST},
1280 {"PMTU", VAR_SERVER | VAR_HOST},
1281 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1283 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1284 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1285 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1286 {"TCPOnly", VAR_SERVER | VAR_HOST},
1287 {"Weight", VAR_HOST},
1291 static int cmd_config(int argc, char *argv[]) {
1293 fprintf(stderr, "Invalid number of arguments.\n");
1298 if(!strcasecmp(argv[1], "get")) {
1300 } else if(!strcasecmp(argv[1], "add")) {
1301 argv++, argc--, action = 1;
1302 } else if(!strcasecmp(argv[1], "del")) {
1303 argv++, argc--, action = -1;
1304 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1305 argv++, argc--, action = 0;
1309 fprintf(stderr, "Invalid number of arguments.\n");
1313 // Concatenate the rest of the command line
1314 strncpy(line, argv[1], sizeof line - 1);
1315 for(int i = 2; i < argc; i++) {
1316 strncat(line, " ", sizeof line - 1 - strlen(line));
1317 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1320 // Liberal parsing into node name, variable name and value.
1326 len = strcspn(line, "\t =");
1328 value += strspn(value, "\t ");
1331 value += strspn(value, "\t ");
1334 variable = strchr(line, '.');
1343 fprintf(stderr, "No variable given.\n");
1347 if(action >= 0 && !*value) {
1348 fprintf(stderr, "No value for variable given.\n");
1352 if(action < -1 && *value)
1355 /* Some simple checks. */
1358 for(int i = 0; variables[i].name; i++) {
1359 if(strcasecmp(variables[i].name, variable))
1363 variable = (char *)variables[i].name;
1365 /* Discourage use of obsolete variables. */
1367 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1369 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1371 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1376 /* Don't put server variables in host config files */
1378 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1380 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1382 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1387 /* Should this go into our own host config file? */
1389 if(!node && !(variables[i].type & VAR_SERVER)) {
1390 node = get_my_name();
1398 if(node && !check_id(node)) {
1399 fprintf(stderr, "Invalid name for node.\n");
1404 if(force || action < 0) {
1405 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1407 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1412 // Open the right configuration file.
1415 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1417 filename = tinc_conf;
1419 FILE *f = fopen(filename, "r");
1421 if(action < 0 || errno != ENOENT) {
1422 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1426 // If it doesn't exist, create it.
1427 f = fopen(filename, "a+");
1429 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1432 fprintf(stderr, "Created configuration file %s.\n", filename);
1436 char *tmpfile = NULL;
1440 xasprintf(&tmpfile, "%s.config.tmp", filename);
1441 tf = fopen(tmpfile, "w");
1443 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1449 // Copy the file, making modifications on the fly, unless we are just getting a value.
1453 bool removed = false;
1456 while(fgets(buf1, sizeof buf1, f)) {
1457 buf1[sizeof buf1 - 1] = 0;
1458 strncpy(buf2, buf1, sizeof buf2);
1460 // Parse line in a simple way
1464 len = strcspn(buf2, "\t =");
1465 bvalue = buf2 + len;
1466 bvalue += strspn(bvalue, "\t ");
1467 if(*bvalue == '=') {
1469 bvalue += strspn(bvalue, "\t ");
1475 if(!strcasecmp(buf2, variable)) {
1479 printf("%s\n", bvalue);
1481 } else if(action == -1) {
1482 if(!*value || !strcasecmp(bvalue, value)) {
1487 } else if(action == 0) {
1488 // Already set? Delete the rest...
1491 // Otherwise, replace.
1492 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1493 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1502 // Copy original line...
1503 if(fputs(buf1, tf) < 0) {
1504 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1508 // Add newline if it is missing...
1509 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1510 if(fputc('\n', tf) < 0) {
1511 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1518 // Make sure we read everything...
1519 if(ferror(f) || !feof(f)) {
1520 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1525 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1529 // Add new variable if necessary.
1530 if(action > 0 || (action == 0 && !set)) {
1531 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1532 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1539 fprintf(stderr, "No matching configuration variables found.\n");
1543 // Make sure we wrote everything...
1545 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1549 // Could we find what we had to remove?
1550 if(action < 0 && !removed) {
1552 fprintf(stderr, "No configuration variables deleted.\n");
1556 // Replace the configuration file with the new one
1558 if(remove(filename)) {
1559 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1563 if(rename(tmpfile, filename)) {
1564 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1568 // Silently try notifying a running tincd of changes.
1569 if(connect_tincd(false))
1570 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1575 bool check_id(const char *name) {
1579 for(int i = 0; i < strlen(name); i++) {
1580 if(!isalnum(name[i]) && name[i] != '_')
1587 static int cmd_init(int argc, char *argv[]) {
1588 if(!access(tinc_conf, F_OK)) {
1589 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1594 fprintf(stderr, "Too many arguments!\n");
1596 } else if(argc < 2) {
1599 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1601 if(!fgets(buf, sizeof buf, stdin)) {
1602 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1605 int len = rstrip(buf);
1607 fprintf(stderr, "No name given!\n");
1612 fprintf(stderr, "No Name given!\n");
1616 name = strdup(argv[1]);
1618 fprintf(stderr, "No Name given!\n");
1623 if(!check_id(name)) {
1624 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1628 if(mkdir(confdir, 0755) && errno != EEXIST) {
1629 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1633 if(mkdir(confbase, 0755) && errno != EEXIST) {
1634 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1638 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1639 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1643 FILE *f = fopen(tinc_conf, "w");
1645 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1649 fprintf(f, "Name = %s\n", name);
1652 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1657 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1658 if(access(filename, F_OK)) {
1659 FILE *f = fopen(filename, "w");
1661 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1664 fchmod(fileno(f), 0755);
1665 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");
1674 static int cmd_generate_keys(int argc, char *argv[]) {
1676 fprintf(stderr, "Too many arguments!\n");
1680 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1683 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1685 fprintf(stderr, "Too many arguments!\n");
1689 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1692 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1694 fprintf(stderr, "Too many arguments!\n");
1698 return !ecdsa_keygen(true);
1701 static int cmd_help(int argc, char *argv[]) {
1706 static int cmd_version(int argc, char *argv[]) {
1708 fprintf(stderr, "Too many arguments!\n");
1716 static int cmd_info(int argc, char *argv[]) {
1718 fprintf(stderr, "Invalid number of arguments.\n");
1722 if(!connect_tincd(true))
1725 return info(fd, argv[1]);
1728 static const char *conffiles[] = {
1739 static int cmd_edit(int argc, char *argv[]) {
1741 fprintf(stderr, "Invalid number of arguments.\n");
1745 char *filename = NULL;
1747 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1748 for(int i = 0; conffiles[i]; i++) {
1749 if(!strcmp(argv[1], conffiles[i])) {
1750 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1759 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1760 char *dash = strchr(argv[1], '-');
1763 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1764 fprintf(stderr, "Invalid configuration filename.\n");
1772 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1774 xasprintf(&command, "edit \"%s\"", filename);
1776 int result = system(command);
1780 // Silently try notifying a running tincd of changes.
1781 if(connect_tincd(false))
1782 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1787 static int export(const char *name, FILE *out) {
1789 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1790 FILE *in = fopen(filename, "r");
1792 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1796 fprintf(out, "Name = %s\n", name);
1798 while(fgets(buf, sizeof buf, in)) {
1799 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1804 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1813 static int cmd_export(int argc, char *argv[]) {
1815 fprintf(stderr, "Too many arguments!\n");
1819 char *name = get_my_name();
1823 int result = export(name, stdout);
1829 static int cmd_export_all(int argc, char *argv[]) {
1831 fprintf(stderr, "Too many arguments!\n");
1835 DIR *dir = opendir(hosts_dir);
1837 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1845 while((ent = readdir(dir))) {
1846 if(!check_id(ent->d_name))
1852 printf("#---------------------------------------------------------------#\n");
1854 result |= export(ent->d_name, stdout);
1863 static int cmd_import(int argc, char *argv[]) {
1865 fprintf(stderr, "Too many arguments!\n");
1874 char *filename = NULL;
1876 bool firstline = true;
1878 while(fgets(buf, sizeof buf, in)) {
1879 if(sscanf(buf, "Name = %s", name) == 1) {
1882 if(!check_id(name)) {
1883 fprintf(stderr, "Invalid Name in input!\n");
1891 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1893 if(!force && !access(filename, F_OK)) {
1894 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1899 out = fopen(filename, "w");
1901 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1907 } else if(firstline) {
1908 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1913 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1917 if(fputs(buf, out) < 0) {
1918 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1928 fprintf(stderr, "Imported %d host configuration files.\n", count);
1931 fprintf(stderr, "No host configuration files imported.\n");
1936 static int cmd_exchange(int argc, char *argv[]) {
1937 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1940 static int cmd_exchange_all(int argc, char *argv[]) {
1941 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1944 static const struct {
1945 const char *command;
1946 int (*function)(int argc, char *argv[]);
1948 {"start", cmd_start},
1950 {"restart", cmd_restart},
1951 {"reload", cmd_reload},
1953 {"purge", cmd_purge},
1954 {"debug", cmd_debug},
1955 {"retry", cmd_retry},
1956 {"connect", cmd_connect},
1957 {"disconnect", cmd_disconnect},
1962 {"config", cmd_config},
1964 {"generate-keys", cmd_generate_keys},
1965 {"generate-rsa-keys", cmd_generate_rsa_keys},
1966 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1968 {"version", cmd_version},
1971 {"export", cmd_export},
1972 {"export-all", cmd_export_all},
1973 {"import", cmd_import},
1974 {"exchange", cmd_exchange},
1975 {"exchange-all", cmd_exchange_all},
1979 #ifdef HAVE_READLINE
1980 static char *complete_command(const char *text, int state) {
1988 while(commands[i].command) {
1989 if(!strncasecmp(commands[i].command, text, strlen(text)))
1990 return xstrdup(commands[i].command);
1997 static char *complete_dump(const char *text, int state) {
1998 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2007 if(!strncasecmp(matches[i], text, strlen(text)))
2008 return xstrdup(matches[i]);
2015 static char *complete_config(const char *text, int state) {
2016 const char *sub[] = {"get", "set", "add", "del"};
2020 if(!strchr(rl_line_buffer + 7, ' '))
2024 for(int i = 0; i < 4; i++) {
2025 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2037 while(i < 0 || variables[i].name) {
2038 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2039 return xstrdup(sub[i + 4]);
2041 char *dot = strchr(text, '.');
2043 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2045 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2049 if(!strncasecmp(variables[i].name, text, strlen(text)))
2050 return xstrdup(variables[i].name);
2059 static char *complete_info(const char *text, int state) {
2063 if(!connect_tincd(false))
2065 // Check the list of nodes
2066 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2067 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2070 while(recvline(fd, line, sizeof line)) {
2072 int n = sscanf(line, "%d %d %s", &code, &req, item);
2082 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2086 if(!strncmp(item, text, strlen(text)))
2087 return xstrdup(strip_weight(item));
2093 static char *complete_nothing(const char *text, int state) {
2097 static char **completion (const char *text, int start, int end) {
2098 char **matches = NULL;
2101 matches = rl_completion_matches(text, complete_command);
2102 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2103 matches = rl_completion_matches(text, complete_dump);
2104 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2105 matches = rl_completion_matches(text, complete_config);
2106 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2107 matches = rl_completion_matches(text, complete_info);
2113 static int cmd_shell(int argc, char *argv[]) {
2115 xasprintf(&prompt, "%s> ", identname);
2119 int maxargs = argc + 16;
2120 char **nargv = xmalloc(maxargs * sizeof *nargv);
2122 for(int i = 0; i < argc; i++)
2125 #ifdef HAVE_READLINE
2126 rl_readline_name = "tinc";
2127 rl_completion_entry_function = complete_nothing;
2128 rl_attempted_completion_function = completion;
2129 rl_filename_completion_desired = 0;
2134 #ifdef HAVE_READLINE
2138 rl_basic_word_break_characters = "\t\n ";
2139 line = readline(prompt);
2141 copy = xstrdup(line);
2143 line = fgets(buf, sizeof buf, stdin);
2147 fputs(prompt, stdout);
2149 line = fgets(buf, sizeof buf, stdin);
2155 /* Ignore comments */
2163 char *p = line + strspn(line, " \t\n");
2164 char *next = strtok(p, " \t\n");
2167 if(nargc >= maxargs) {
2168 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2171 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2176 next = strtok(NULL, " \t\n");
2182 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2187 for(int i = 0; commands[i].command; i++) {
2188 if(!strcasecmp(nargv[argc], commands[i].command)) {
2189 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2195 #ifdef HAVE_READLINE
2201 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2214 int main(int argc, char *argv[]) {
2215 program_name = argv[0];
2219 if(!parse_options(argc, argv))
2223 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2224 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2236 tty = isatty(0) && isatty(1);
2239 return cmd_shell(argc, argv);
2241 for(int i = 0; commands[i].command; i++) {
2242 if(!strcasecmp(argv[optind], commands[i].command))
2243 return commands[i].function(argc - optind, argv + optind);
2246 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);