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"
35 #include "invitation.h"
43 #define mkdir(a, b) mkdir(a)
44 #define SCRIPTEXTENSION ".bat"
46 #define SCRIPTEXTENSION ""
49 static char **orig_argv;
52 /* If nonzero, display usage information and exit. */
53 static bool show_help = false;
55 /* If nonzero, print the version on standard output and exit. */
56 static bool show_version = false;
58 static char *name = NULL;
59 static char controlcookie[1025];
60 char *tinc_conf = NULL;
61 char *hosts_dir = NULL;
64 // Horrible global variables...
71 static bool force = false;
73 bool confbasegiven = false;
74 bool netnamegiven = false;
77 static struct WSAData wsa_state;
80 static struct option const long_options[] = {
81 {"config", required_argument, NULL, 'c'},
82 {"net", required_argument, NULL, 'n'},
83 {"help", no_argument, NULL, 1},
84 {"version", no_argument, NULL, 2},
85 {"pidfile", required_argument, NULL, 3},
86 {"force", no_argument, NULL, 4},
90 static void version(void) {
91 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
92 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
93 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
94 "See the AUTHORS file for a complete list.\n\n"
95 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
96 "and you are welcome to redistribute it under certain conditions;\n"
97 "see the file COPYING for details.\n");
100 static void usage(bool status) {
102 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
104 printf("Usage: %s [options] command\n\n", program_name);
105 printf("Valid options are:\n"
106 " -c, --config=DIR Read configuration options from DIR.\n"
107 " -n, --net=NETNAME Connect to net NETNAME.\n"
108 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
109 " --help Display this help and exit.\n"
110 " --version Output version information and exit.\n"
112 "Valid commands are:\n"
113 " init [name] Create initial configuration files.\n"
114 " get VARIABLE Print current value of VARIABLE\n"
115 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
116 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
117 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
118 " start [tincd options] Start tincd.\n"
119 " stop Stop tincd.\n"
120 " restart Restart tincd.\n"
121 " reload Partially reload configuration of running tincd.\n"
122 " pid Show PID of currently running tincd.\n"
123 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
124 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
125 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
126 " dump Dump a list of one of the following things:\n"
127 " [reachable] nodes - all known nodes in the VPN\n"
128 " edges - all known connections in the VPN\n"
129 " subnets - all known subnets in the VPN\n"
130 " connections - all meta connections with ourself\n"
131 " [di]graph - graph of the VPN in dotty format\n"
132 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
133 " purge Purge unreachable nodes\n"
134 " debug N Set debug level\n"
135 " retry Retry all outgoing connections\n"
136 " disconnect NODE Close meta connection with NODE\n"
138 " top Show real-time statistics\n"
140 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
141 " log [level] Dump log output [up to the specified level]\n"
142 " export Export host configuration of local node to standard output\n"
143 " export-all Export all host configuration files to standard output\n"
144 " import [--force] Import host configuration file(s) from standard input\n"
145 " exchange [--force] Same as export followed by import\n"
146 " exchange-all [--force] Same as export-all followed by import\n"
147 " invite NODE [...] Generate an invitation for NODE\n"
148 " join INVITATION Join a VPN using an INVITIATION\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:", long_options, &option_index)) != EOF) {
160 case 0: /* long option */
163 case 'c': /* config file */
164 confbase = xstrdup(optarg);
165 confbasegiven = true;
168 case 'n': /* net name given */
169 netname = xstrdup(optarg);
172 case 1: /* show help */
176 case 2: /* show version */
180 case 3: /* open control socket here */
181 pidfilename = xstrdup(optarg);
188 case '?': /* wrong options */
197 if(!netname && (netname = getenv("NETNAME")))
198 netname = xstrdup(netname);
200 /* netname "." is special: a "top-level name" */
202 if(netname && (!*netname || !strcmp(netname, "."))) {
207 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
208 fprintf(stderr, "Invalid character in netname!\n");
215 static void disable_old_keys(const char *filename, const char *what) {
216 char tmpfile[PATH_MAX] = "";
218 bool disabled = false;
223 r = fopen(filename, "r");
227 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
229 w = fopen(tmpfile, "w");
231 while(fgets(buf, sizeof buf, r)) {
232 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
233 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
239 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
245 if(block || ecdsapubkey)
247 if(fputs(buf, w) < 0) {
253 if(block && !strncmp(buf, "-----END ", 9))
260 if(ferror(r) || fclose(r) < 0)
265 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
272 // We cannot atomically replace files on Windows.
273 char bakfile[PATH_MAX] = "";
274 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
275 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
276 rename(bakfile, filename);
278 if(rename(tmpfile, filename)) {
280 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
285 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
292 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
298 /* Check stdin and stdout */
300 /* Ask for a file and/or directory name. */
301 fprintf(stdout, "Please enter a file to save %s to [%s]: ", what, filename);
304 if(fgets(buf, sizeof buf, stdin) == NULL) {
305 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
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");
468 bool recvline(int fd, char *line, size_t len) {
469 char *newline = NULL;
474 while(!(newline = memchr(buffer, '\n', blen))) {
475 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
476 if(result == -1 && errno == EINTR)
483 if(newline - buffer >= len)
486 len = newline - buffer;
488 memcpy(line, buffer, len);
490 memmove(buffer, newline + 1, blen - len - 1);
496 bool recvdata(int fd, char *data, size_t len) {
501 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
502 if(result == -1 && errno == EINTR)
509 memcpy(data, buffer, len);
510 memmove(buffer, buffer + len, blen - len);
516 bool sendline(int fd, char *format, ...) {
517 static char buffer[4096];
522 va_start(ap, format);
523 blen = vsnprintf(buffer, sizeof buffer, format, ap);
526 if(blen < 1 || blen >= sizeof buffer)
533 int result = send(fd, p, blen, 0);
534 if(result == -1 && errno == EINTR)
545 static void pcap(int fd, FILE *out, int snaplen) {
546 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
554 uint32_t tz_accuracy;
561 snaplen ?: sizeof data,
574 fwrite(&header, sizeof header, 1, out);
578 while(recvline(fd, line, sizeof line)) {
580 int n = sscanf(line, "%d %d %d", &code, &req, &len);
581 gettimeofday(&tv, NULL);
582 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
584 if(!recvdata(fd, data, len))
586 packet.tv_sec = tv.tv_sec;
587 packet.tv_usec = tv.tv_usec;
589 packet.origlen = len;
590 fwrite(&packet, sizeof packet, 1, out);
591 fwrite(data, len, 1, out);
596 static void logcontrol(int fd, FILE *out, int level) {
597 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
601 while(recvline(fd, line, sizeof line)) {
603 int n = sscanf(line, "%d %d %d", &code, &req, &len);
604 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
606 if(!recvdata(fd, data, len))
608 fwrite(data, len, 1, out);
615 static bool remove_service(void) {
616 SC_HANDLE manager = NULL;
617 SC_HANDLE service = NULL;
618 SERVICE_STATUS status = {0};
620 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
622 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
626 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
629 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
633 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
634 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
636 fprintf(stderr, "%s service stopped\n", identname);
638 if(!DeleteService(service)) {
639 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
643 fprintf(stderr, "%s service removed\n", identname);
649 bool connect_tincd(bool verbose) {
654 struct timeval tv = {0, 0};
655 if(select(fd + 1, &r, NULL, NULL, &tv)) {
656 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
664 FILE *f = fopen(pidfilename, "r");
667 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
674 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
676 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
684 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
686 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
692 struct sockaddr_un sa;
693 sa.sun_family = AF_UNIX;
694 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
696 fd = socket(AF_UNIX, SOCK_STREAM, 0);
699 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
703 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
705 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
711 struct addrinfo hints = {
712 .ai_family = AF_UNSPEC,
713 .ai_socktype = SOCK_STREAM,
714 .ai_protocol = IPPROTO_TCP,
718 struct addrinfo *res = NULL;
720 if(getaddrinfo(host, port, &hints, &res) || !res) {
722 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
726 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
729 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
734 unsigned long arg = 0;
736 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
738 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
742 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
744 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
756 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
758 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
764 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
766 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
768 fprintf(stderr, "Could not fully establish control socket connection\n");
778 static int cmd_start(int argc, char *argv[]) {
779 if(connect_tincd(false)) {
781 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
783 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
788 char *slash = strrchr(program_name, '/');
791 if ((c = strrchr(program_name, '\\')) > slash)
796 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
801 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
804 for(int i = 1; i < optind; i++)
805 nargv[nargc++] = orig_argv[i];
806 for(int i = 1; i < argc; i++)
807 nargv[nargc++] = argv[i];
811 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
816 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
822 exit(execvp(c, nargv));
827 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
828 fprintf(stderr, "Error starting %s\n", c);
836 static int cmd_stop(int argc, char *argv[]) {
838 fprintf(stderr, "Too many arguments!\n");
843 if(!connect_tincd(true)) {
845 if(kill(pid, SIGTERM)) {
846 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
850 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
851 waitpid(pid, NULL, 0);
858 sendline(fd, "%d %d", CONTROL, REQ_STOP);
860 while(recvline(fd, line, sizeof line)) {
861 // Wait for tincd to close the connection...
864 if(!remove_service())
874 static int cmd_restart(int argc, char *argv[]) {
875 cmd_stop(argc, argv);
876 return cmd_start(argc, argv);
879 static int cmd_reload(int argc, char *argv[]) {
881 fprintf(stderr, "Too many arguments!\n");
885 if(!connect_tincd(true))
888 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
889 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
890 fprintf(stderr, "Could not reload configuration.\n");
898 static int cmd_dump(int argc, char *argv[]) {
899 bool only_reachable = false;
901 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
902 if(strcasecmp(argv[2], "nodes")) {
903 fprintf(stderr, "`reachable' only supported for nodes.\n");
907 only_reachable = true;
913 fprintf(stderr, "Invalid number of arguments.\n");
918 if(!connect_tincd(true))
923 if(!strcasecmp(argv[1], "nodes"))
924 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
925 else if(!strcasecmp(argv[1], "edges"))
926 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
927 else if(!strcasecmp(argv[1], "subnets"))
928 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
929 else if(!strcasecmp(argv[1], "connections"))
930 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
931 else if(!strcasecmp(argv[1], "graph")) {
932 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
933 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
935 } else if(!strcasecmp(argv[1], "digraph")) {
936 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
937 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
940 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
947 else if(do_graph == 2)
948 printf("digraph {\n");
950 while(recvline(fd, line, sizeof line)) {
951 char node1[4096], node2[4096];
952 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
954 if(do_graph && req == REQ_DUMP_NODES)
973 int cipher, digest, maclength, compression, distance, socket, weight;
974 short int pmtu, minmtu, maxmtu;
975 unsigned int options, status_int;
976 node_status_t status;
977 long int last_state_change;
980 case REQ_DUMP_NODES: {
981 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);
983 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
987 memcpy(&status, &status_int, sizeof status);
990 const char *color = "black";
991 if(!strcmp(host, "MYSELF"))
993 else if(!status.reachable)
995 else if(strcmp(via, node))
997 else if(!status.validkey)
1001 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1003 if(only_reachable && !status.reachable)
1005 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",
1006 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1010 case REQ_DUMP_EDGES: {
1011 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1013 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1018 float w = 1 + 65536.0 / weight;
1019 if(do_graph == 1 && strcmp(node1, node2) > 0)
1020 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1021 else if(do_graph == 2)
1022 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1024 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1028 case REQ_DUMP_SUBNETS: {
1029 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1031 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1034 printf("%s owner %s\n", strip_weight(subnet), node);
1037 case REQ_DUMP_CONNECTIONS: {
1038 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1040 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1043 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1047 fprintf(stderr, "Unable to parse dump from tincd.\n");
1052 fprintf(stderr, "Error receiving dump.\n");
1056 static int cmd_purge(int argc, char *argv[]) {
1058 fprintf(stderr, "Too many arguments!\n");
1062 if(!connect_tincd(true))
1065 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1066 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1067 fprintf(stderr, "Could not purge old information.\n");
1074 static int cmd_debug(int argc, char *argv[]) {
1076 fprintf(stderr, "Invalid number of arguments.\n");
1080 if(!connect_tincd(true))
1083 int debuglevel = atoi(argv[1]);
1086 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1087 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1088 fprintf(stderr, "Could not set debug level.\n");
1092 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1096 static int cmd_retry(int argc, char *argv[]) {
1098 fprintf(stderr, "Too many arguments!\n");
1102 if(!connect_tincd(true))
1105 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1106 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1107 fprintf(stderr, "Could not retry outgoing connections.\n");
1114 static int cmd_connect(int argc, char *argv[]) {
1116 fprintf(stderr, "Invalid number of arguments.\n");
1120 if(!check_id(argv[1])) {
1121 fprintf(stderr, "Invalid name for node.\n");
1125 if(!connect_tincd(true))
1128 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1129 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1130 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1137 static int cmd_disconnect(int argc, char *argv[]) {
1139 fprintf(stderr, "Invalid number of arguments.\n");
1143 if(!check_id(argv[1])) {
1144 fprintf(stderr, "Invalid name for node.\n");
1148 if(!connect_tincd(true))
1151 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1152 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1153 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1160 static int cmd_top(int argc, char *argv[]) {
1162 fprintf(stderr, "Too many arguments!\n");
1167 if(!connect_tincd(true))
1173 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1178 static int cmd_pcap(int argc, char *argv[]) {
1180 fprintf(stderr, "Too many arguments!\n");
1184 if(!connect_tincd(true))
1187 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1192 static void sigint_handler(int sig) {
1193 fprintf(stderr, "\n");
1194 shutdown(fd, SHUT_RDWR);
1198 static int cmd_log(int argc, char *argv[]) {
1200 fprintf(stderr, "Too many arguments!\n");
1204 if(!connect_tincd(true))
1208 signal(SIGINT, sigint_handler);
1211 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1214 signal(SIGINT, SIG_DFL);
1222 static int cmd_pid(int argc, char *argv[]) {
1224 fprintf(stderr, "Too many arguments!\n");
1228 if(!connect_tincd(true) && !pid)
1231 printf("%d\n", pid);
1235 int rstrip(char *value) {
1236 int len = strlen(value);
1237 while(len && strchr("\t\r\n ", value[len - 1]))
1242 char *get_my_name(bool verbose) {
1243 FILE *f = fopen(tinc_conf, "r");
1246 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1252 while(fgets(buf, sizeof buf, f)) {
1253 int len = strcspn(buf, "\t =");
1255 value += strspn(value, "\t ");
1258 value += strspn(value, "\t ");
1263 if(strcasecmp(buf, "Name"))
1267 return strdup(value);
1273 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1277 const var_t variables[] = {
1278 /* Server configuration */
1279 {"AddressFamily", VAR_SERVER},
1280 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1281 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1282 {"BindToInterface", VAR_SERVER},
1283 {"Broadcast", VAR_SERVER | VAR_SAFE},
1284 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1285 {"DecrementTTL", VAR_SERVER},
1286 {"Device", VAR_SERVER},
1287 {"DeviceType", VAR_SERVER},
1288 {"DirectOnly", VAR_SERVER},
1289 {"ECDSAPrivateKeyFile", VAR_SERVER},
1290 {"ExperimentalProtocol", VAR_SERVER},
1291 {"Forwarding", VAR_SERVER},
1292 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1293 {"Hostnames", VAR_SERVER},
1294 {"IffOneQueue", VAR_SERVER},
1295 {"Interface", VAR_SERVER},
1296 {"KeyExpire", VAR_SERVER},
1297 {"LocalDiscovery", VAR_SERVER},
1298 {"MACExpire", VAR_SERVER},
1299 {"MaxConnectionBurst", VAR_SERVER},
1300 {"MaxOutputBufferSize", VAR_SERVER},
1301 {"MaxTimeout", VAR_SERVER},
1302 {"Mode", VAR_SERVER | VAR_SAFE},
1303 {"Name", VAR_SERVER},
1304 {"PingInterval", VAR_SERVER},
1305 {"PingTimeout", VAR_SERVER},
1306 {"PriorityInheritance", VAR_SERVER},
1307 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1308 {"PrivateKeyFile", VAR_SERVER},
1309 {"ProcessPriority", VAR_SERVER},
1310 {"Proxy", VAR_SERVER},
1311 {"ReplayWindow", VAR_SERVER},
1312 {"ScriptsExtension", VAR_SERVER},
1313 {"ScriptsInterpreter", VAR_SERVER},
1314 {"StrictSubnets", VAR_SERVER},
1315 {"TunnelServer", VAR_SERVER},
1316 {"UDPRcvBuf", VAR_SERVER},
1317 {"UDPSndBuf", VAR_SERVER},
1318 {"VDEGroup", VAR_SERVER},
1319 {"VDEPort", VAR_SERVER},
1320 /* Host configuration */
1321 {"Address", VAR_HOST | VAR_MULTIPLE},
1322 {"Cipher", VAR_SERVER | VAR_HOST},
1323 {"ClampMSS", VAR_SERVER | VAR_HOST},
1324 {"Compression", VAR_SERVER | VAR_HOST},
1325 {"Digest", VAR_SERVER | VAR_HOST},
1326 {"ECDSAPublicKey", VAR_HOST},
1327 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1328 {"IndirectData", VAR_SERVER | VAR_HOST},
1329 {"MACLength", VAR_SERVER | VAR_HOST},
1330 {"PMTU", VAR_SERVER | VAR_HOST},
1331 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1333 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1334 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1335 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1336 {"TCPOnly", VAR_SERVER | VAR_HOST},
1337 {"Weight", VAR_HOST | VAR_SAFE},
1341 static int cmd_config(int argc, char *argv[]) {
1343 fprintf(stderr, "Invalid number of arguments.\n");
1347 if(strcasecmp(argv[0], "config"))
1351 if(!strcasecmp(argv[1], "get")) {
1353 } else if(!strcasecmp(argv[1], "add")) {
1354 argv++, argc--, action = 1;
1355 } else if(!strcasecmp(argv[1], "del")) {
1356 argv++, argc--, action = -1;
1357 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1358 argv++, argc--, action = 0;
1362 fprintf(stderr, "Invalid number of arguments.\n");
1366 // Concatenate the rest of the command line
1367 strncpy(line, argv[1], sizeof line - 1);
1368 for(int i = 2; i < argc; i++) {
1369 strncat(line, " ", sizeof line - 1 - strlen(line));
1370 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1373 // Liberal parsing into node name, variable name and value.
1379 len = strcspn(line, "\t =");
1381 value += strspn(value, "\t ");
1384 value += strspn(value, "\t ");
1387 variable = strchr(line, '.');
1396 fprintf(stderr, "No variable given.\n");
1400 if(action >= 0 && !*value) {
1401 fprintf(stderr, "No value for variable given.\n");
1405 if(action < -1 && *value)
1408 /* Some simple checks. */
1411 for(int i = 0; variables[i].name; i++) {
1412 if(strcasecmp(variables[i].name, variable))
1416 variable = (char *)variables[i].name;
1418 /* Discourage use of obsolete variables. */
1420 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1422 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1424 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1429 /* Don't put server variables in host config files */
1431 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1433 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1435 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1440 /* Should this go into our own host config file? */
1442 if(!node && !(variables[i].type & VAR_SERVER)) {
1443 node = get_my_name(true);
1451 if(node && !check_id(node)) {
1452 fprintf(stderr, "Invalid name for node.\n");
1457 if(force || action < 0) {
1458 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1460 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1465 // Open the right configuration file.
1468 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1470 filename = tinc_conf;
1472 FILE *f = fopen(filename, "r");
1474 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1478 char *tmpfile = NULL;
1482 xasprintf(&tmpfile, "%s.config.tmp", filename);
1483 tf = fopen(tmpfile, "w");
1485 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1491 // Copy the file, making modifications on the fly, unless we are just getting a value.
1495 bool removed = false;
1498 while(fgets(buf1, sizeof buf1, f)) {
1499 buf1[sizeof buf1 - 1] = 0;
1500 strncpy(buf2, buf1, sizeof buf2);
1502 // Parse line in a simple way
1506 len = strcspn(buf2, "\t =");
1507 bvalue = buf2 + len;
1508 bvalue += strspn(bvalue, "\t ");
1509 if(*bvalue == '=') {
1511 bvalue += strspn(bvalue, "\t ");
1517 if(!strcasecmp(buf2, variable)) {
1521 printf("%s\n", bvalue);
1523 } else if(action == -1) {
1524 if(!*value || !strcasecmp(bvalue, value)) {
1529 } else if(action == 0) {
1530 // Already set? Delete the rest...
1533 // Otherwise, replace.
1534 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1535 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1544 // Copy original line...
1545 if(fputs(buf1, tf) < 0) {
1546 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1550 // Add newline if it is missing...
1551 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1552 if(fputc('\n', tf) < 0) {
1553 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1560 // Make sure we read everything...
1561 if(ferror(f) || !feof(f)) {
1562 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1567 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1571 // Add new variable if necessary.
1572 if(action > 0 || (action == 0 && !set)) {
1573 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1574 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1581 fprintf(stderr, "No matching configuration variables found.\n");
1585 // Make sure we wrote everything...
1587 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1591 // Could we find what we had to remove?
1592 if(action < 0 && !removed) {
1594 fprintf(stderr, "No configuration variables deleted.\n");
1598 // Replace the configuration file with the new one
1600 if(remove(filename)) {
1601 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1605 if(rename(tmpfile, filename)) {
1606 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1610 // Silently try notifying a running tincd of changes.
1611 if(connect_tincd(false))
1612 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1617 bool check_id(const char *name) {
1621 for(int i = 0; i < strlen(name); i++) {
1622 if(!isalnum(name[i]) && name[i] != '_')
1629 static int cmd_init(int argc, char *argv[]) {
1630 if(!access(tinc_conf, F_OK)) {
1631 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1636 fprintf(stderr, "Too many arguments!\n");
1638 } else if(argc < 2) {
1641 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1643 if(!fgets(buf, sizeof buf, stdin)) {
1644 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1647 int len = rstrip(buf);
1649 fprintf(stderr, "No name given!\n");
1654 fprintf(stderr, "No Name given!\n");
1658 name = strdup(argv[1]);
1660 fprintf(stderr, "No Name given!\n");
1665 if(!check_id(name)) {
1666 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1670 if(mkdir(confdir, 0755) && errno != EEXIST) {
1671 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1675 if(mkdir(confbase, 0755) && errno != EEXIST) {
1676 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1680 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1681 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1685 FILE *f = fopen(tinc_conf, "w");
1687 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1691 fprintf(f, "Name = %s\n", name);
1694 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1699 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1700 if(access(filename, F_OK)) {
1701 FILE *f = fopen(filename, "w");
1703 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1706 fchmod(fileno(f), 0755);
1707 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");
1716 static int cmd_generate_keys(int argc, char *argv[]) {
1718 fprintf(stderr, "Too many arguments!\n");
1723 name = get_my_name(false);
1725 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1728 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1730 fprintf(stderr, "Too many arguments!\n");
1735 name = get_my_name(false);
1737 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1740 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1742 fprintf(stderr, "Too many arguments!\n");
1747 name = get_my_name(false);
1749 return !ecdsa_keygen(true);
1752 static int cmd_help(int argc, char *argv[]) {
1757 static int cmd_version(int argc, char *argv[]) {
1759 fprintf(stderr, "Too many arguments!\n");
1767 static int cmd_info(int argc, char *argv[]) {
1769 fprintf(stderr, "Invalid number of arguments.\n");
1773 if(!connect_tincd(true))
1776 return info(fd, argv[1]);
1779 static const char *conffiles[] = {
1790 static int cmd_edit(int argc, char *argv[]) {
1792 fprintf(stderr, "Invalid number of arguments.\n");
1796 char *filename = NULL;
1798 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1799 for(int i = 0; conffiles[i]; i++) {
1800 if(!strcmp(argv[1], conffiles[i])) {
1801 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1810 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1811 char *dash = strchr(argv[1], '-');
1814 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1815 fprintf(stderr, "Invalid configuration filename.\n");
1823 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1825 xasprintf(&command, "edit \"%s\"", filename);
1827 int result = system(command);
1831 // Silently try notifying a running tincd of changes.
1832 if(connect_tincd(false))
1833 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1838 static int export(const char *name, FILE *out) {
1840 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1841 FILE *in = fopen(filename, "r");
1843 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1847 fprintf(out, "Name = %s\n", name);
1849 while(fgets(buf, sizeof buf, in)) {
1850 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1855 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1864 static int cmd_export(int argc, char *argv[]) {
1866 fprintf(stderr, "Too many arguments!\n");
1870 char *name = get_my_name(true);
1874 int result = export(name, stdout);
1882 static int cmd_export_all(int argc, char *argv[]) {
1884 fprintf(stderr, "Too many arguments!\n");
1888 DIR *dir = opendir(hosts_dir);
1890 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1898 while((ent = readdir(dir))) {
1899 if(!check_id(ent->d_name))
1905 printf("#---------------------------------------------------------------#\n");
1907 result |= export(ent->d_name, stdout);
1916 static int cmd_import(int argc, char *argv[]) {
1918 fprintf(stderr, "Too many arguments!\n");
1927 char *filename = NULL;
1929 bool firstline = true;
1931 while(fgets(buf, sizeof buf, in)) {
1932 if(sscanf(buf, "Name = %s", name) == 1) {
1935 if(!check_id(name)) {
1936 fprintf(stderr, "Invalid Name in input!\n");
1944 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1946 if(!force && !access(filename, F_OK)) {
1947 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1952 out = fopen(filename, "w");
1954 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1960 } else if(firstline) {
1961 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1966 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1970 if(fputs(buf, out) < 0) {
1971 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1981 fprintf(stderr, "Imported %d host configuration files.\n", count);
1984 fprintf(stderr, "No host configuration files imported.\n");
1989 static int cmd_exchange(int argc, char *argv[]) {
1990 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1993 static int cmd_exchange_all(int argc, char *argv[]) {
1994 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1997 static const struct {
1998 const char *command;
1999 int (*function)(int argc, char *argv[]);
2002 {"start", cmd_start},
2004 {"restart", cmd_restart},
2005 {"reload", cmd_reload},
2007 {"purge", cmd_purge},
2008 {"debug", cmd_debug},
2009 {"retry", cmd_retry},
2010 {"connect", cmd_connect},
2011 {"disconnect", cmd_disconnect},
2016 {"config", cmd_config, true},
2017 {"add", cmd_config},
2018 {"del", cmd_config},
2019 {"get", cmd_config},
2020 {"set", cmd_config},
2022 {"generate-keys", cmd_generate_keys},
2023 {"generate-rsa-keys", cmd_generate_rsa_keys},
2024 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2026 {"version", cmd_version},
2029 {"export", cmd_export},
2030 {"export-all", cmd_export_all},
2031 {"import", cmd_import},
2032 {"exchange", cmd_exchange},
2033 {"exchange-all", cmd_exchange_all},
2034 {"invite", cmd_invite},
2039 #ifdef HAVE_READLINE
2040 static char *complete_command(const char *text, int state) {
2048 while(commands[i].command) {
2049 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2050 return xstrdup(commands[i].command);
2057 static char *complete_dump(const char *text, int state) {
2058 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2067 if(!strncasecmp(matches[i], text, strlen(text)))
2068 return xstrdup(matches[i]);
2075 static char *complete_config(const char *text, int state) {
2083 while(variables[i].name) {
2084 char *dot = strchr(text, '.');
2086 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2088 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2092 if(!strncasecmp(variables[i].name, text, strlen(text)))
2093 return xstrdup(variables[i].name);
2101 static char *complete_info(const char *text, int state) {
2105 if(!connect_tincd(false))
2107 // Check the list of nodes
2108 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2109 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2112 while(recvline(fd, line, sizeof line)) {
2114 int n = sscanf(line, "%d %d %s", &code, &req, item);
2124 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2128 if(!strncmp(item, text, strlen(text)))
2129 return xstrdup(strip_weight(item));
2135 static char *complete_nothing(const char *text, int state) {
2139 static char **completion (const char *text, int start, int end) {
2140 char **matches = NULL;
2143 matches = rl_completion_matches(text, complete_command);
2144 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2145 matches = rl_completion_matches(text, complete_dump);
2146 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2147 matches = rl_completion_matches(text, complete_config);
2148 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2149 matches = rl_completion_matches(text, complete_config);
2150 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2151 matches = rl_completion_matches(text, complete_config);
2152 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2153 matches = rl_completion_matches(text, complete_config);
2154 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2155 matches = rl_completion_matches(text, complete_info);
2161 static int cmd_shell(int argc, char *argv[]) {
2163 xasprintf(&prompt, "%s> ", identname);
2167 int maxargs = argc + 16;
2168 char **nargv = xmalloc(maxargs * sizeof *nargv);
2170 for(int i = 0; i < argc; i++)
2173 #ifdef HAVE_READLINE
2174 rl_readline_name = "tinc";
2175 rl_completion_entry_function = complete_nothing;
2176 rl_attempted_completion_function = completion;
2177 rl_filename_completion_desired = 0;
2182 #ifdef HAVE_READLINE
2186 rl_basic_word_break_characters = "\t\n ";
2187 line = readline(prompt);
2189 copy = xstrdup(line);
2191 line = fgets(buf, sizeof buf, stdin);
2195 fputs(prompt, stdout);
2197 line = fgets(buf, sizeof buf, stdin);
2203 /* Ignore comments */
2211 char *p = line + strspn(line, " \t\n");
2212 char *next = strtok(p, " \t\n");
2215 if(nargc >= maxargs) {
2216 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2219 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2224 next = strtok(NULL, " \t\n");
2230 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2235 for(int i = 0; commands[i].command; i++) {
2236 if(!strcasecmp(nargv[argc], commands[i].command)) {
2237 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2243 #ifdef HAVE_READLINE
2249 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2262 int main(int argc, char *argv[]) {
2263 program_name = argv[0];
2267 if(!parse_options(argc, argv))
2271 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2272 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2286 tty = isatty(0) && isatty(1);
2289 return cmd_shell(argc, argv);
2291 for(int i = 0; commands[i].command; i++) {
2292 if(!strcasecmp(argv[optind], commands[i].command))
2293 return commands[i].function(argc - optind, argv + optind);
2296 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);