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 SCRIPTEXTENSION ".bat"
45 #define SCRIPTEXTENSION ""
48 static char **orig_argv;
51 /* If nonzero, display usage information and exit. */
52 static bool show_help = false;
54 /* If nonzero, print the version on standard output and exit. */
55 static bool show_version = false;
57 static char *name = NULL;
58 static char controlcookie[1025];
59 char *tinc_conf = NULL;
60 char *hosts_dir = NULL;
63 // Horrible global variables...
70 static bool force = false;
72 bool confbasegiven = false;
73 bool netnamegiven = false;
76 static struct WSAData wsa_state;
79 static struct option const long_options[] = {
80 {"config", required_argument, NULL, 'c'},
81 {"net", required_argument, NULL, 'n'},
82 {"help", no_argument, NULL, 1},
83 {"version", no_argument, NULL, 2},
84 {"pidfile", required_argument, NULL, 3},
85 {"force", no_argument, NULL, 4},
89 static void version(void) {
90 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
91 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
92 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
93 "See the AUTHORS file for a complete list.\n\n"
94 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
95 "and you are welcome to redistribute it under certain conditions;\n"
96 "see the file COPYING for details.\n");
99 static void usage(bool status) {
101 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
103 printf("Usage: %s [options] command\n\n", program_name);
104 printf("Valid options are:\n"
105 " -c, --config=DIR Read configuration options from DIR.\n"
106 " -n, --net=NETNAME Connect to net NETNAME.\n"
107 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
108 " --help Display this help and exit.\n"
109 " --version Output version information and exit.\n"
111 "Valid commands are:\n"
112 " init [name] Create initial configuration files.\n"
113 " get VARIABLE Print current value of VARIABLE\n"
114 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
115 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
116 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
117 " start [tincd options] Start tincd.\n"
118 " stop Stop tincd.\n"
119 " restart [tincd options] Restart tincd.\n"
120 " reload Partially reload configuration of running tincd.\n"
121 " pid Show PID of currently running tincd.\n"
122 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
123 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
124 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
125 " dump Dump a list of one of the following things:\n"
126 " [reachable] nodes - all known nodes in the VPN\n"
127 " edges - all known connections in the VPN\n"
128 " subnets - all known subnets in the VPN\n"
129 " connections - all meta connections with ourself\n"
130 " [di]graph - graph of the VPN in dotty format\n"
131 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
132 " purge Purge unreachable nodes\n"
133 " debug N Set debug level\n"
134 " retry Retry all outgoing connections\n"
135 " disconnect NODE Close meta connection with NODE\n"
137 " top Show real-time statistics\n"
139 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
140 " log [level] Dump log output [up to the specified level]\n"
141 " export Export host configuration of local node to standard output\n"
142 " export-all Export all host configuration files to standard output\n"
143 " import [--force] Import host configuration file(s) from standard input\n"
144 " exchange [--force] Same as export followed by import\n"
145 " exchange-all [--force] Same as export-all followed by import\n"
146 " invite NODE [...] Generate an invitation for NODE\n"
147 " join INVITATION Join a VPN using an INVITIATION\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:", long_options, &option_index)) != EOF) {
159 case 0: /* long option */
162 case 'c': /* config file */
163 confbase = xstrdup(optarg);
164 confbasegiven = true;
167 case 'n': /* net name given */
168 netname = xstrdup(optarg);
171 case 1: /* show help */
175 case 2: /* show version */
179 case 3: /* 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");
231 /* Let the temporary file have the same permissions as the original. */
234 struct stat st = {.st_mode = 0600};
235 fstat(fileno(r), &st);
236 fchmod(fileno(w), st.st_mode);
240 while(fgets(buf, sizeof buf, r)) {
241 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
242 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
248 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
254 if(block || ecdsapubkey)
256 if(fputs(buf, w) < 0) {
262 if(block && !strncmp(buf, "-----END ", 9))
269 if(ferror(r) || fclose(r) < 0)
274 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
281 // We cannot atomically replace files on Windows.
282 char bakfile[PATH_MAX] = "";
283 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
284 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
285 rename(bakfile, filename);
287 if(rename(tmpfile, filename)) {
289 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
294 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
301 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
307 /* Check stdin and stdout */
309 /* Ask for a file and/or directory name. */
310 fprintf(stdout, "Please enter a file to save %s to [%s]: ", what, filename);
313 if(fgets(buf, sizeof buf, stdin) == NULL) {
314 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
318 size_t len = strlen(buf);
327 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
329 if(filename[0] != '/') {
331 /* The directory is a relative path or a filename. */
332 directory = get_current_dir_name();
333 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
337 disable_old_keys(filename, what);
339 /* Open it first to keep the inode busy */
341 r = fopen(filename, mode);
344 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
352 Generate a public/private ECDSA keypair, and ask for a file to store
355 static bool ecdsa_keygen(bool ask) {
358 char *pubname, *privname;
360 fprintf(stderr, "Generating ECDSA keypair:\n");
362 if(!(key = ecdsa_generate())) {
363 fprintf(stderr, "Error during key generation!\n");
366 fprintf(stderr, "Done.\n");
368 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
369 f = ask_and_open(privname, "private ECDSA key", "a", ask);
376 /* Make it unreadable for others. */
377 fchmod(fileno(f), 0600);
380 if(!ecdsa_write_pem_private_key(key, f)) {
381 fprintf(stderr, "Error writing private key!\n");
390 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
392 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
394 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
400 char *pubkey = ecdsa_get_base64_public_key(key);
401 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
411 Generate a public/private RSA keypair, and ask for a file to store
414 static bool rsa_keygen(int bits, bool ask) {
417 char *pubname, *privname;
419 fprintf(stderr, "Generating %d bits keys:\n", bits);
421 if(!(key = rsa_generate(bits, 0x10001))) {
422 fprintf(stderr, "Error during key generation!\n");
425 fprintf(stderr, "Done.\n");
427 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
428 f = ask_and_open(privname, "private RSA key", "a", ask);
435 /* Make it unreadable for others. */
436 fchmod(fileno(f), 0600);
439 if(!rsa_write_pem_private_key(key, f)) {
440 fprintf(stderr, "Error writing private key!\n");
449 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
451 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
453 f = ask_and_open(pubname, "public RSA key", "a", ask);
459 if(!rsa_write_pem_public_key(key, f)) {
460 fprintf(stderr, "Error writing public key!\n");
475 bool recvline(int fd, char *line, size_t len) {
476 char *newline = NULL;
481 while(!(newline = memchr(buffer, '\n', blen))) {
482 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
483 if(result == -1 && errno == EINTR)
490 if(newline - buffer >= len)
493 len = newline - buffer;
495 memcpy(line, buffer, len);
497 memmove(buffer, newline + 1, blen - len - 1);
503 bool recvdata(int fd, char *data, size_t len) {
508 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
509 if(result == -1 && errno == EINTR)
516 memcpy(data, buffer, len);
517 memmove(buffer, buffer + len, blen - len);
523 bool sendline(int fd, char *format, ...) {
524 static char buffer[4096];
529 va_start(ap, format);
530 blen = vsnprintf(buffer, sizeof buffer, format, ap);
533 if(blen < 1 || blen >= sizeof buffer)
540 int result = send(fd, p, blen, 0);
541 if(result == -1 && errno == EINTR)
552 static void pcap(int fd, FILE *out, int snaplen) {
553 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
561 uint32_t tz_accuracy;
568 snaplen ?: sizeof data,
581 fwrite(&header, sizeof header, 1, out);
585 while(recvline(fd, line, sizeof line)) {
587 int n = sscanf(line, "%d %d %d", &code, &req, &len);
588 gettimeofday(&tv, NULL);
589 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
591 if(!recvdata(fd, data, len))
593 packet.tv_sec = tv.tv_sec;
594 packet.tv_usec = tv.tv_usec;
596 packet.origlen = len;
597 fwrite(&packet, sizeof packet, 1, out);
598 fwrite(data, len, 1, out);
603 static void logcontrol(int fd, FILE *out, int level) {
604 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
608 while(recvline(fd, line, sizeof line)) {
610 int n = sscanf(line, "%d %d %d", &code, &req, &len);
611 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
613 if(!recvdata(fd, data, len))
615 fwrite(data, len, 1, out);
622 static bool remove_service(void) {
623 SC_HANDLE manager = NULL;
624 SC_HANDLE service = NULL;
625 SERVICE_STATUS status = {0};
627 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
629 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
633 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
636 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
640 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
641 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
643 fprintf(stderr, "%s service stopped\n", identname);
645 if(!DeleteService(service)) {
646 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
650 fprintf(stderr, "%s service removed\n", identname);
656 bool connect_tincd(bool verbose) {
661 struct timeval tv = {0, 0};
662 if(select(fd + 1, &r, NULL, NULL, &tv)) {
663 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
671 FILE *f = fopen(pidfilename, "r");
674 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
681 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
683 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
691 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
693 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
699 struct sockaddr_un sa;
700 sa.sun_family = AF_UNIX;
701 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
703 fd = socket(AF_UNIX, SOCK_STREAM, 0);
706 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
710 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
712 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
718 struct addrinfo hints = {
719 .ai_family = AF_UNSPEC,
720 .ai_socktype = SOCK_STREAM,
721 .ai_protocol = IPPROTO_TCP,
725 struct addrinfo *res = NULL;
727 if(getaddrinfo(host, port, &hints, &res) || !res) {
729 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
733 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
736 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
741 unsigned long arg = 0;
743 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
745 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
749 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
751 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
763 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
765 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
771 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
773 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
775 fprintf(stderr, "Could not fully establish control socket connection\n");
785 static int cmd_start(int argc, char *argv[]) {
786 if(connect_tincd(false)) {
788 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
790 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
795 char *slash = strrchr(program_name, '/');
798 if ((c = strrchr(program_name, '\\')) > slash)
803 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
808 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
811 for(int i = 1; i < optind; i++)
812 nargv[nargc++] = orig_argv[i];
813 for(int i = 1; i < argc; i++)
814 nargv[nargc++] = argv[i];
818 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
823 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
829 exit(execvp(c, nargv));
833 int status = -1, result;
835 signal(SIGINT, SIG_IGN);
837 result = waitpid(pid, &status, 0);
839 signal(SIGINT, SIG_DFL);
842 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
843 fprintf(stderr, "Error starting %s\n", c);
851 static int cmd_stop(int argc, char *argv[]) {
853 fprintf(stderr, "Too many arguments!\n");
858 if(!connect_tincd(true)) {
860 if(kill(pid, SIGTERM)) {
861 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
865 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
866 waitpid(pid, NULL, 0);
873 sendline(fd, "%d %d", CONTROL, REQ_STOP);
875 while(recvline(fd, line, sizeof line)) {
876 // Wait for tincd to close the connection...
879 if(!remove_service())
889 static int cmd_restart(int argc, char *argv[]) {
891 return cmd_start(argc, argv);
894 static int cmd_reload(int argc, char *argv[]) {
896 fprintf(stderr, "Too many arguments!\n");
900 if(!connect_tincd(true))
903 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
904 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
905 fprintf(stderr, "Could not reload configuration.\n");
913 static int cmd_dump(int argc, char *argv[]) {
914 bool only_reachable = false;
916 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
917 if(strcasecmp(argv[2], "nodes")) {
918 fprintf(stderr, "`reachable' only supported for nodes.\n");
922 only_reachable = true;
928 fprintf(stderr, "Invalid number of arguments.\n");
933 if(!connect_tincd(true))
938 if(!strcasecmp(argv[1], "nodes"))
939 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
940 else if(!strcasecmp(argv[1], "edges"))
941 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
942 else if(!strcasecmp(argv[1], "subnets"))
943 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
944 else if(!strcasecmp(argv[1], "connections"))
945 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
946 else if(!strcasecmp(argv[1], "graph")) {
947 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
948 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
950 } else if(!strcasecmp(argv[1], "digraph")) {
951 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
952 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
955 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
962 else if(do_graph == 2)
963 printf("digraph {\n");
965 while(recvline(fd, line, sizeof line)) {
966 char node1[4096], node2[4096];
967 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
969 if(do_graph && req == REQ_DUMP_NODES)
988 int cipher, digest, maclength, compression, distance, socket, weight;
989 short int pmtu, minmtu, maxmtu;
990 unsigned int options, status_int;
991 node_status_t status;
992 long int last_state_change;
995 case REQ_DUMP_NODES: {
996 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);
998 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1002 memcpy(&status, &status_int, sizeof status);
1005 const char *color = "black";
1006 if(!strcmp(host, "MYSELF"))
1008 else if(!status.reachable)
1010 else if(strcmp(via, node))
1012 else if(!status.validkey)
1016 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1018 if(only_reachable && !status.reachable)
1020 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",
1021 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1025 case REQ_DUMP_EDGES: {
1026 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1028 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1033 float w = 1 + 65536.0 / weight;
1034 if(do_graph == 1 && strcmp(node1, node2) > 0)
1035 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1036 else if(do_graph == 2)
1037 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1039 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1043 case REQ_DUMP_SUBNETS: {
1044 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1046 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1049 printf("%s owner %s\n", strip_weight(subnet), node);
1052 case REQ_DUMP_CONNECTIONS: {
1053 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1055 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1058 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1062 fprintf(stderr, "Unable to parse dump from tincd.\n");
1067 fprintf(stderr, "Error receiving dump.\n");
1071 static int cmd_purge(int argc, char *argv[]) {
1073 fprintf(stderr, "Too many arguments!\n");
1077 if(!connect_tincd(true))
1080 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1081 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1082 fprintf(stderr, "Could not purge old information.\n");
1089 static int cmd_debug(int argc, char *argv[]) {
1091 fprintf(stderr, "Invalid number of arguments.\n");
1095 if(!connect_tincd(true))
1098 int debuglevel = atoi(argv[1]);
1101 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1102 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1103 fprintf(stderr, "Could not set debug level.\n");
1107 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1111 static int cmd_retry(int argc, char *argv[]) {
1113 fprintf(stderr, "Too many arguments!\n");
1117 if(!connect_tincd(true))
1120 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1121 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1122 fprintf(stderr, "Could not retry outgoing connections.\n");
1129 static int cmd_connect(int argc, char *argv[]) {
1131 fprintf(stderr, "Invalid number of arguments.\n");
1135 if(!check_id(argv[1])) {
1136 fprintf(stderr, "Invalid name for node.\n");
1140 if(!connect_tincd(true))
1143 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1144 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1145 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1152 static int cmd_disconnect(int argc, char *argv[]) {
1154 fprintf(stderr, "Invalid number of arguments.\n");
1158 if(!check_id(argv[1])) {
1159 fprintf(stderr, "Invalid name for node.\n");
1163 if(!connect_tincd(true))
1166 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1167 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1168 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1175 static int cmd_top(int argc, char *argv[]) {
1177 fprintf(stderr, "Too many arguments!\n");
1182 if(!connect_tincd(true))
1188 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1193 static int cmd_pcap(int argc, char *argv[]) {
1195 fprintf(stderr, "Too many arguments!\n");
1199 if(!connect_tincd(true))
1202 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1207 static void sigint_handler(int sig) {
1208 fprintf(stderr, "\n");
1209 shutdown(fd, SHUT_RDWR);
1213 static int cmd_log(int argc, char *argv[]) {
1215 fprintf(stderr, "Too many arguments!\n");
1219 if(!connect_tincd(true))
1223 signal(SIGINT, sigint_handler);
1226 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1229 signal(SIGINT, SIG_DFL);
1237 static int cmd_pid(int argc, char *argv[]) {
1239 fprintf(stderr, "Too many arguments!\n");
1243 if(!connect_tincd(true) && !pid)
1246 printf("%d\n", pid);
1250 int rstrip(char *value) {
1251 int len = strlen(value);
1252 while(len && strchr("\t\r\n ", value[len - 1]))
1257 char *get_my_name(bool verbose) {
1258 FILE *f = fopen(tinc_conf, "r");
1261 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1267 while(fgets(buf, sizeof buf, f)) {
1268 int len = strcspn(buf, "\t =");
1270 value += strspn(value, "\t ");
1273 value += strspn(value, "\t ");
1278 if(strcasecmp(buf, "Name"))
1282 return strdup(value);
1288 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1292 const var_t variables[] = {
1293 /* Server configuration */
1294 {"AddressFamily", VAR_SERVER},
1295 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1296 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1297 {"BindToInterface", VAR_SERVER},
1298 {"Broadcast", VAR_SERVER | VAR_SAFE},
1299 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1300 {"DecrementTTL", VAR_SERVER},
1301 {"Device", VAR_SERVER},
1302 {"DeviceType", VAR_SERVER},
1303 {"DirectOnly", VAR_SERVER},
1304 {"ECDSAPrivateKeyFile", VAR_SERVER},
1305 {"ExperimentalProtocol", VAR_SERVER},
1306 {"Forwarding", VAR_SERVER},
1307 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1308 {"Hostnames", VAR_SERVER},
1309 {"IffOneQueue", VAR_SERVER},
1310 {"Interface", VAR_SERVER},
1311 {"KeyExpire", VAR_SERVER},
1312 {"LocalDiscovery", VAR_SERVER},
1313 {"MACExpire", VAR_SERVER},
1314 {"MaxConnectionBurst", VAR_SERVER},
1315 {"MaxOutputBufferSize", VAR_SERVER},
1316 {"MaxTimeout", VAR_SERVER},
1317 {"Mode", VAR_SERVER | VAR_SAFE},
1318 {"Name", VAR_SERVER},
1319 {"PingInterval", VAR_SERVER},
1320 {"PingTimeout", VAR_SERVER},
1321 {"PriorityInheritance", VAR_SERVER},
1322 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1323 {"PrivateKeyFile", VAR_SERVER},
1324 {"ProcessPriority", VAR_SERVER},
1325 {"Proxy", VAR_SERVER},
1326 {"ReplayWindow", VAR_SERVER},
1327 {"ScriptsExtension", VAR_SERVER},
1328 {"ScriptsInterpreter", VAR_SERVER},
1329 {"StrictSubnets", VAR_SERVER},
1330 {"TunnelServer", VAR_SERVER},
1331 {"UDPRcvBuf", VAR_SERVER},
1332 {"UDPSndBuf", VAR_SERVER},
1333 {"VDEGroup", VAR_SERVER},
1334 {"VDEPort", VAR_SERVER},
1335 /* Host configuration */
1336 {"Address", VAR_HOST | VAR_MULTIPLE},
1337 {"Cipher", VAR_SERVER | VAR_HOST},
1338 {"ClampMSS", VAR_SERVER | VAR_HOST},
1339 {"Compression", VAR_SERVER | VAR_HOST},
1340 {"Digest", VAR_SERVER | VAR_HOST},
1341 {"ECDSAPublicKey", VAR_HOST},
1342 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1343 {"IndirectData", VAR_SERVER | VAR_HOST},
1344 {"MACLength", VAR_SERVER | VAR_HOST},
1345 {"PMTU", VAR_SERVER | VAR_HOST},
1346 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1348 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1349 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1350 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1351 {"TCPOnly", VAR_SERVER | VAR_HOST},
1352 {"Weight", VAR_HOST | VAR_SAFE},
1356 static int cmd_config(int argc, char *argv[]) {
1358 fprintf(stderr, "Invalid number of arguments.\n");
1362 if(strcasecmp(argv[0], "config"))
1366 if(!strcasecmp(argv[1], "get")) {
1368 } else if(!strcasecmp(argv[1], "add")) {
1369 argv++, argc--, action = 1;
1370 } else if(!strcasecmp(argv[1], "del")) {
1371 argv++, argc--, action = -1;
1372 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1373 argv++, argc--, action = 0;
1377 fprintf(stderr, "Invalid number of arguments.\n");
1381 // Concatenate the rest of the command line
1382 strncpy(line, argv[1], sizeof line - 1);
1383 for(int i = 2; i < argc; i++) {
1384 strncat(line, " ", sizeof line - 1 - strlen(line));
1385 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1388 // Liberal parsing into node name, variable name and value.
1394 len = strcspn(line, "\t =");
1396 value += strspn(value, "\t ");
1399 value += strspn(value, "\t ");
1402 variable = strchr(line, '.');
1411 fprintf(stderr, "No variable given.\n");
1415 if(action >= 0 && !*value) {
1416 fprintf(stderr, "No value for variable given.\n");
1420 if(action < -1 && *value)
1423 /* Some simple checks. */
1425 bool warnonremove = false;
1427 for(int i = 0; variables[i].name; i++) {
1428 if(strcasecmp(variables[i].name, variable))
1432 variable = (char *)variables[i].name;
1434 /* Discourage use of obsolete variables. */
1436 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1438 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1440 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1445 /* Don't put server variables in host config files */
1447 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1449 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1451 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1456 /* Should this go into our own host config file? */
1458 if(!node && !(variables[i].type & VAR_SERVER)) {
1459 node = get_my_name(true);
1464 /* Change "add" into "set" for variables that do not allow multiple occurences.
1465 Turn on warnings when it seems variables might be removed unintentionally. */
1467 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1468 warnonremove = true;
1470 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1471 warnonremove = true;
1477 if(node && !check_id(node)) {
1478 fprintf(stderr, "Invalid name for node.\n");
1483 if(force || action < 0) {
1484 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1486 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1491 // Open the right configuration file.
1494 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1496 filename = tinc_conf;
1498 FILE *f = fopen(filename, "r");
1500 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1504 char *tmpfile = NULL;
1508 xasprintf(&tmpfile, "%s.config.tmp", filename);
1509 tf = fopen(tmpfile, "w");
1511 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1517 // Copy the file, making modifications on the fly, unless we are just getting a value.
1521 bool removed = false;
1524 while(fgets(buf1, sizeof buf1, f)) {
1525 buf1[sizeof buf1 - 1] = 0;
1526 strncpy(buf2, buf1, sizeof buf2);
1528 // Parse line in a simple way
1532 len = strcspn(buf2, "\t =");
1533 bvalue = buf2 + len;
1534 bvalue += strspn(bvalue, "\t ");
1535 if(*bvalue == '=') {
1537 bvalue += strspn(bvalue, "\t ");
1543 if(!strcasecmp(buf2, variable)) {
1547 printf("%s\n", bvalue);
1549 } else if(action == -1) {
1550 if(!*value || !strcasecmp(bvalue, value)) {
1555 } else if(action == 0) {
1556 // Warn if "set" was used for variables that can occur multiple times
1557 if(warnonremove && strcasecmp(bvalue, value))
1558 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1560 // Already set? Delete the rest...
1564 // Otherwise, replace.
1565 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1566 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1575 // Copy original line...
1576 if(fputs(buf1, tf) < 0) {
1577 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1581 // Add newline if it is missing...
1582 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1583 if(fputc('\n', tf) < 0) {
1584 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1591 // Make sure we read everything...
1592 if(ferror(f) || !feof(f)) {
1593 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1598 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1602 // Add new variable if necessary.
1603 if(action > 0 || (action == 0 && !set)) {
1604 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1605 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1612 fprintf(stderr, "No matching configuration variables found.\n");
1616 // Make sure we wrote everything...
1618 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1622 // Could we find what we had to remove?
1623 if(action < 0 && !removed) {
1625 fprintf(stderr, "No configuration variables deleted.\n");
1629 // Replace the configuration file with the new one
1631 if(remove(filename)) {
1632 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1636 if(rename(tmpfile, filename)) {
1637 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1641 // Silently try notifying a running tincd of changes.
1642 if(connect_tincd(false))
1643 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1648 bool check_id(const char *name) {
1652 for(int i = 0; i < strlen(name); i++) {
1653 if(!isalnum(name[i]) && name[i] != '_')
1660 static bool try_bind(int port) {
1661 struct addrinfo *ai = NULL;
1662 struct addrinfo hint = {
1663 .ai_flags = AI_PASSIVE,
1664 .ai_family = AF_UNSPEC,
1665 .ai_socktype = SOCK_STREAM,
1666 .ai_protocol = IPPROTO_TCP,
1670 snprintf(portstr, sizeof portstr, "%d", port);
1672 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1676 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1679 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1689 int check_port(char *name) {
1693 fprintf(stderr, "Warning: could not bind to port 655. ");
1695 for(int i = 0; i < 100; i++) {
1696 int port = 0x1000 + (rand() & 0x7fff);
1697 if(try_bind(port)) {
1699 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1700 FILE *f = fopen(filename, "a");
1703 fprintf(stderr, "Please change tinc's Port manually.\n");
1707 fprintf(f, "Port = %d\n", port);
1709 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1714 fprintf(stderr, "Please change tinc's Port manually.\n");
1718 static int cmd_init(int argc, char *argv[]) {
1719 if(!access(tinc_conf, F_OK)) {
1720 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1725 fprintf(stderr, "Too many arguments!\n");
1727 } else if(argc < 2) {
1730 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1732 if(!fgets(buf, sizeof buf, stdin)) {
1733 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1736 int len = rstrip(buf);
1738 fprintf(stderr, "No name given!\n");
1743 fprintf(stderr, "No Name given!\n");
1747 name = strdup(argv[1]);
1749 fprintf(stderr, "No Name given!\n");
1754 if(!check_id(name)) {
1755 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1759 if(mkdir(confdir, 0755) && errno != EEXIST) {
1760 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1764 if(mkdir(confbase, 0755) && errno != EEXIST) {
1765 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1769 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1770 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1774 FILE *f = fopen(tinc_conf, "w");
1776 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1780 fprintf(f, "Name = %s\n", name);
1783 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1790 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1791 if(access(filename, F_OK)) {
1792 FILE *f = fopen(filename, "w");
1794 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1797 mode_t mask = umask(0);
1799 fchmod(fileno(f), 0755 & ~mask);
1800 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");
1809 static int cmd_generate_keys(int argc, char *argv[]) {
1811 fprintf(stderr, "Too many arguments!\n");
1816 name = get_my_name(false);
1818 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1821 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1823 fprintf(stderr, "Too many arguments!\n");
1828 name = get_my_name(false);
1830 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1833 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1835 fprintf(stderr, "Too many arguments!\n");
1840 name = get_my_name(false);
1842 return !ecdsa_keygen(true);
1845 static int cmd_help(int argc, char *argv[]) {
1850 static int cmd_version(int argc, char *argv[]) {
1852 fprintf(stderr, "Too many arguments!\n");
1860 static int cmd_info(int argc, char *argv[]) {
1862 fprintf(stderr, "Invalid number of arguments.\n");
1866 if(!connect_tincd(true))
1869 return info(fd, argv[1]);
1872 static const char *conffiles[] = {
1883 static int cmd_edit(int argc, char *argv[]) {
1885 fprintf(stderr, "Invalid number of arguments.\n");
1889 char *filename = NULL;
1891 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1892 for(int i = 0; conffiles[i]; i++) {
1893 if(!strcmp(argv[1], conffiles[i])) {
1894 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1903 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1904 char *dash = strchr(argv[1], '-');
1907 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1908 fprintf(stderr, "Invalid configuration filename.\n");
1916 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1918 xasprintf(&command, "edit \"%s\"", filename);
1920 int result = system(command);
1924 // Silently try notifying a running tincd of changes.
1925 if(connect_tincd(false))
1926 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1931 static int export(const char *name, FILE *out) {
1933 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1934 FILE *in = fopen(filename, "r");
1936 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1940 fprintf(out, "Name = %s\n", name);
1942 while(fgets(buf, sizeof buf, in)) {
1943 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1948 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1957 static int cmd_export(int argc, char *argv[]) {
1959 fprintf(stderr, "Too many arguments!\n");
1963 char *name = get_my_name(true);
1967 int result = export(name, stdout);
1975 static int cmd_export_all(int argc, char *argv[]) {
1977 fprintf(stderr, "Too many arguments!\n");
1981 DIR *dir = opendir(hosts_dir);
1983 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1991 while((ent = readdir(dir))) {
1992 if(!check_id(ent->d_name))
1998 printf("#---------------------------------------------------------------#\n");
2000 result |= export(ent->d_name, stdout);
2009 static int cmd_import(int argc, char *argv[]) {
2011 fprintf(stderr, "Too many arguments!\n");
2020 char *filename = NULL;
2022 bool firstline = true;
2024 while(fgets(buf, sizeof buf, in)) {
2025 if(sscanf(buf, "Name = %s", name) == 1) {
2028 if(!check_id(name)) {
2029 fprintf(stderr, "Invalid Name in input!\n");
2037 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2039 if(!force && !access(filename, F_OK)) {
2040 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2045 out = fopen(filename, "w");
2047 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2053 } else if(firstline) {
2054 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2059 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2063 if(fputs(buf, out) < 0) {
2064 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2074 fprintf(stderr, "Imported %d host configuration files.\n", count);
2077 fprintf(stderr, "No host configuration files imported.\n");
2082 static int cmd_exchange(int argc, char *argv[]) {
2083 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2086 static int cmd_exchange_all(int argc, char *argv[]) {
2087 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2090 static const struct {
2091 const char *command;
2092 int (*function)(int argc, char *argv[]);
2095 {"start", cmd_start},
2097 {"restart", cmd_restart},
2098 {"reload", cmd_reload},
2100 {"purge", cmd_purge},
2101 {"debug", cmd_debug},
2102 {"retry", cmd_retry},
2103 {"connect", cmd_connect},
2104 {"disconnect", cmd_disconnect},
2109 {"config", cmd_config, true},
2110 {"add", cmd_config},
2111 {"del", cmd_config},
2112 {"get", cmd_config},
2113 {"set", cmd_config},
2115 {"generate-keys", cmd_generate_keys},
2116 {"generate-rsa-keys", cmd_generate_rsa_keys},
2117 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2119 {"version", cmd_version},
2122 {"export", cmd_export},
2123 {"export-all", cmd_export_all},
2124 {"import", cmd_import},
2125 {"exchange", cmd_exchange},
2126 {"exchange-all", cmd_exchange_all},
2127 {"invite", cmd_invite},
2132 #ifdef HAVE_READLINE
2133 static char *complete_command(const char *text, int state) {
2141 while(commands[i].command) {
2142 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2143 return xstrdup(commands[i].command);
2150 static char *complete_dump(const char *text, int state) {
2151 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2160 if(!strncasecmp(matches[i], text, strlen(text)))
2161 return xstrdup(matches[i]);
2168 static char *complete_config(const char *text, int state) {
2176 while(variables[i].name) {
2177 char *dot = strchr(text, '.');
2179 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2181 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2185 if(!strncasecmp(variables[i].name, text, strlen(text)))
2186 return xstrdup(variables[i].name);
2194 static char *complete_info(const char *text, int state) {
2198 if(!connect_tincd(false))
2200 // Check the list of nodes
2201 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2202 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2205 while(recvline(fd, line, sizeof line)) {
2207 int n = sscanf(line, "%d %d %s", &code, &req, item);
2217 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2221 if(!strncmp(item, text, strlen(text)))
2222 return xstrdup(strip_weight(item));
2228 static char *complete_nothing(const char *text, int state) {
2232 static char **completion (const char *text, int start, int end) {
2233 char **matches = NULL;
2236 matches = rl_completion_matches(text, complete_command);
2237 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2238 matches = rl_completion_matches(text, complete_dump);
2239 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2240 matches = rl_completion_matches(text, complete_config);
2241 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2242 matches = rl_completion_matches(text, complete_config);
2243 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2244 matches = rl_completion_matches(text, complete_config);
2245 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2246 matches = rl_completion_matches(text, complete_config);
2247 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2248 matches = rl_completion_matches(text, complete_info);
2254 static int cmd_shell(int argc, char *argv[]) {
2256 xasprintf(&prompt, "%s> ", identname);
2260 int maxargs = argc + 16;
2261 char **nargv = xmalloc(maxargs * sizeof *nargv);
2263 for(int i = 0; i < argc; i++)
2266 #ifdef HAVE_READLINE
2267 rl_readline_name = "tinc";
2268 rl_completion_entry_function = complete_nothing;
2269 rl_attempted_completion_function = completion;
2270 rl_filename_completion_desired = 0;
2275 #ifdef HAVE_READLINE
2279 rl_basic_word_break_characters = "\t\n ";
2280 line = readline(prompt);
2282 copy = xstrdup(line);
2284 line = fgets(buf, sizeof buf, stdin);
2288 fputs(prompt, stdout);
2290 line = fgets(buf, sizeof buf, stdin);
2296 /* Ignore comments */
2304 char *p = line + strspn(line, " \t\n");
2305 char *next = strtok(p, " \t\n");
2308 if(nargc >= maxargs) {
2309 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2312 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2317 next = strtok(NULL, " \t\n");
2323 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2328 for(int i = 0; commands[i].command; i++) {
2329 if(!strcasecmp(nargv[argc], commands[i].command)) {
2330 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2336 #ifdef HAVE_READLINE
2342 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2355 int main(int argc, char *argv[]) {
2356 program_name = argv[0];
2360 if(!parse_options(argc, argv))
2364 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2365 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2380 tty = isatty(0) && isatty(1);
2383 return cmd_shell(argc, argv);
2385 for(int i = 0; commands[i].command; i++) {
2386 if(!strcasecmp(argv[optind], commands[i].command))
2387 return commands[i].function(argc - optind, argv + optind);
2390 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);