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"
42 static char **orig_argv;
45 /* If nonzero, display usage information and exit. */
46 static bool show_help = false;
48 /* If nonzero, print the version on standard output and exit. */
49 static bool show_version = false;
51 static char *name = NULL;
52 static char controlcookie[1025];
53 char *tinc_conf = NULL;
54 char *hosts_dir = NULL;
57 // Horrible global variables...
64 static bool force = false;
66 bool confbasegiven = false;
67 bool netnamegiven = false;
68 char *scriptinterpreter = NULL;
69 char *scriptextension = "";
71 static struct option const long_options[] = {
72 {"config", required_argument, NULL, 'c'},
73 {"net", required_argument, NULL, 'n'},
74 {"help", no_argument, NULL, 1},
75 {"version", no_argument, NULL, 2},
76 {"pidfile", required_argument, NULL, 3},
77 {"force", no_argument, NULL, 4},
81 static void version(void) {
82 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
83 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
84 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
85 "See the AUTHORS file for a complete list.\n\n"
86 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
87 "and you are welcome to redistribute it under certain conditions;\n"
88 "see the file COPYING for details.\n");
91 static void usage(bool status) {
93 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
95 printf("Usage: %s [options] command\n\n", program_name);
96 printf("Valid options are:\n"
97 " -c, --config=DIR Read configuration options from DIR.\n"
98 " -n, --net=NETNAME Connect to net NETNAME.\n"
99 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
100 " --help Display this help and exit.\n"
101 " --version Output version information and exit.\n"
103 "Valid commands are:\n"
104 " init [name] Create initial configuration files.\n"
105 " get VARIABLE Print current value of VARIABLE\n"
106 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
107 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
108 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
109 " start [tincd options] Start tincd.\n"
110 " stop Stop tincd.\n"
111 " restart [tincd options] Restart tincd.\n"
112 " reload Partially reload configuration of running tincd.\n"
113 " pid Show PID of currently running tincd.\n"
114 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
115 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
116 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
117 " dump Dump a list of one of the following things:\n"
118 " [reachable] nodes - all known nodes in the VPN\n"
119 " edges - all known connections in the VPN\n"
120 " subnets - all known subnets in the VPN\n"
121 " connections - all meta connections with ourself\n"
122 " [di]graph - graph of the VPN in dotty format\n"
123 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
124 " purge Purge unreachable nodes\n"
125 " debug N Set debug level\n"
126 " retry Retry all outgoing connections\n"
127 " disconnect NODE Close meta connection with NODE\n"
129 " top Show real-time statistics\n"
131 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
132 " log [level] Dump log output [up to the specified level]\n"
133 " export Export host configuration of local node to standard output\n"
134 " export-all Export all host configuration files to standard output\n"
135 " import [--force] Import host configuration file(s) from standard input\n"
136 " exchange [--force] Same as export followed by import\n"
137 " exchange-all [--force] Same as export-all followed by import\n"
138 " invite NODE [...] Generate an invitation for NODE\n"
139 " join INVITATION Join a VPN using an INVITIATION\n"
141 printf("Report bugs to tinc@tinc-vpn.org.\n");
145 static bool parse_options(int argc, char **argv) {
147 int option_index = 0;
149 while((r = getopt_long(argc, argv, "+c:n:", long_options, &option_index)) != EOF) {
151 case 0: /* long option */
154 case 'c': /* config file */
155 confbase = xstrdup(optarg);
156 confbasegiven = true;
159 case 'n': /* net name given */
160 netname = xstrdup(optarg);
163 case 1: /* show help */
167 case 2: /* show version */
171 case 3: /* open control socket here */
172 pidfilename = xstrdup(optarg);
179 case '?': /* wrong options */
188 if(!netname && (netname = getenv("NETNAME")))
189 netname = xstrdup(netname);
191 /* netname "." is special: a "top-level name" */
193 if(netname && (!*netname || !strcmp(netname, "."))) {
198 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
199 fprintf(stderr, "Invalid character in netname!\n");
206 /* Open a file with the desired permissions, minus the umask.
207 Also, if we want to create an executable file, we call fchmod()
208 to set the executable bits. */
210 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
211 mode_t mask = umask(0);
214 FILE *f = fopen(filename, mode);
216 if((perms & 0444) && f)
217 fchmod(fileno(f), perms);
223 static void disable_old_keys(const char *filename, const char *what) {
224 char tmpfile[PATH_MAX] = "";
226 bool disabled = false;
231 r = fopen(filename, "r");
235 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
237 struct stat st = {.st_mode = 0600};
238 fstat(fileno(r), &st);
239 w = fopenmask(tmpfile, "w", st.st_mode);
241 while(fgets(buf, sizeof buf, r)) {
242 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
243 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
249 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
255 if(block || ecdsapubkey)
257 if(fputs(buf, w) < 0) {
263 if(block && !strncmp(buf, "-----END ", 9))
270 if(ferror(r) || fclose(r) < 0)
275 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
282 // We cannot atomically replace files on Windows.
283 char bakfile[PATH_MAX] = "";
284 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
285 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
286 rename(bakfile, filename);
288 if(rename(tmpfile, filename)) {
290 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
295 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
302 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
308 /* Check stdin and stdout */
310 /* Ask for a file and/or directory name. */
311 fprintf(stdout, "Please enter a file to save %s to [%s]: ", what, filename);
314 if(fgets(buf, sizeof buf, stdin) == NULL) {
315 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
319 size_t len = strlen(buf);
328 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
330 if(filename[0] != '/') {
332 /* The directory is a relative path or a filename. */
333 directory = get_current_dir_name();
334 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
338 disable_old_keys(filename, what);
340 /* Open it first to keep the inode busy */
342 r = fopenmask(filename, mode, perms);
345 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
353 Generate a public/private ECDSA keypair, and ask for a file to store
356 static bool ecdsa_keygen(bool ask) {
359 char *pubname, *privname;
361 fprintf(stderr, "Generating ECDSA keypair:\n");
363 if(!(key = ecdsa_generate())) {
364 fprintf(stderr, "Error during key generation!\n");
367 fprintf(stderr, "Done.\n");
369 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
370 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
376 if(!ecdsa_write_pem_private_key(key, f)) {
377 fprintf(stderr, "Error writing private key!\n");
386 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
388 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
390 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
396 char *pubkey = ecdsa_get_base64_public_key(key);
397 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
407 Generate a public/private RSA keypair, and ask for a file to store
410 static bool rsa_keygen(int bits, bool ask) {
413 char *pubname, *privname;
415 fprintf(stderr, "Generating %d bits keys:\n", bits);
417 if(!(key = rsa_generate(bits, 0x10001))) {
418 fprintf(stderr, "Error during key generation!\n");
421 fprintf(stderr, "Done.\n");
423 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
424 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
430 if(!rsa_write_pem_private_key(key, f)) {
431 fprintf(stderr, "Error writing private key!\n");
440 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
442 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
444 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
450 if(!rsa_write_pem_public_key(key, f)) {
451 fprintf(stderr, "Error writing public key!\n");
466 bool recvline(int fd, char *line, size_t len) {
467 char *newline = NULL;
472 while(!(newline = memchr(buffer, '\n', blen))) {
473 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
474 if(result == -1 && errno == EINTR)
481 if(newline - buffer >= len)
484 len = newline - buffer;
486 memcpy(line, buffer, len);
488 memmove(buffer, newline + 1, blen - len - 1);
494 bool recvdata(int fd, char *data, size_t len) {
499 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
500 if(result == -1 && errno == EINTR)
507 memcpy(data, buffer, len);
508 memmove(buffer, buffer + len, blen - len);
514 bool sendline(int fd, char *format, ...) {
515 static char buffer[4096];
520 va_start(ap, format);
521 blen = vsnprintf(buffer, sizeof buffer, format, ap);
524 if(blen < 1 || blen >= sizeof buffer)
531 int result = send(fd, p, blen, 0);
532 if(result == -1 && errno == EINTR)
543 static void pcap(int fd, FILE *out, int snaplen) {
544 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
552 uint32_t tz_accuracy;
559 snaplen ?: sizeof data,
572 fwrite(&header, sizeof header, 1, out);
576 while(recvline(fd, line, sizeof line)) {
578 int n = sscanf(line, "%d %d %d", &code, &req, &len);
579 gettimeofday(&tv, NULL);
580 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
582 if(!recvdata(fd, data, len))
584 packet.tv_sec = tv.tv_sec;
585 packet.tv_usec = tv.tv_usec;
587 packet.origlen = len;
588 fwrite(&packet, sizeof packet, 1, out);
589 fwrite(data, len, 1, out);
594 static void logcontrol(int fd, FILE *out, int level) {
595 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
599 while(recvline(fd, line, sizeof line)) {
601 int n = sscanf(line, "%d %d %d", &code, &req, &len);
602 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
604 if(!recvdata(fd, data, len))
606 fwrite(data, len, 1, out);
613 static bool remove_service(void) {
614 SC_HANDLE manager = NULL;
615 SC_HANDLE service = NULL;
616 SERVICE_STATUS status = {0};
618 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
620 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
624 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
627 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
631 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
632 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
634 fprintf(stderr, "%s service stopped\n", identname);
636 if(!DeleteService(service)) {
637 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
641 fprintf(stderr, "%s service removed\n", identname);
647 bool connect_tincd(bool verbose) {
652 struct timeval tv = {0, 0};
653 if(select(fd + 1, &r, NULL, NULL, &tv)) {
654 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
662 FILE *f = fopen(pidfilename, "r");
665 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
672 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
674 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
682 struct sockaddr_un sa;
683 sa.sun_family = AF_UNIX;
684 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
686 fd = socket(AF_UNIX, SOCK_STREAM, 0);
689 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
693 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
695 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
701 struct addrinfo hints = {
702 .ai_family = AF_UNSPEC,
703 .ai_socktype = SOCK_STREAM,
704 .ai_protocol = IPPROTO_TCP,
708 struct addrinfo *res = NULL;
710 if(getaddrinfo(host, port, &hints, &res) || !res) {
712 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
716 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
719 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
724 unsigned long arg = 0;
726 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
728 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
732 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
734 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
746 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
748 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
754 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
756 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
758 fprintf(stderr, "Could not fully establish control socket connection\n");
768 static int cmd_start(int argc, char *argv[]) {
769 if(connect_tincd(false)) {
771 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
773 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
778 char *slash = strrchr(program_name, '/');
781 if ((c = strrchr(program_name, '\\')) > slash)
786 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
791 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
794 for(int i = 1; i < optind; i++)
795 nargv[nargc++] = orig_argv[i];
796 for(int i = 1; i < argc; i++)
797 nargv[nargc++] = argv[i];
801 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
806 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
812 exit(execvp(c, nargv));
816 int status = -1, result;
818 signal(SIGINT, SIG_IGN);
820 result = waitpid(pid, &status, 0);
822 signal(SIGINT, SIG_DFL);
825 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
826 fprintf(stderr, "Error starting %s\n", c);
834 static int cmd_stop(int argc, char *argv[]) {
836 fprintf(stderr, "Too many arguments!\n");
841 if(!connect_tincd(true)) {
843 if(kill(pid, SIGTERM)) {
844 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
848 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
849 waitpid(pid, NULL, 0);
856 sendline(fd, "%d %d", CONTROL, REQ_STOP);
858 while(recvline(fd, line, sizeof line)) {
859 // Wait for tincd to close the connection...
862 if(!remove_service())
872 static int cmd_restart(int argc, char *argv[]) {
874 return cmd_start(argc, argv);
877 static int cmd_reload(int argc, char *argv[]) {
879 fprintf(stderr, "Too many arguments!\n");
883 if(!connect_tincd(true))
886 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
887 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
888 fprintf(stderr, "Could not reload configuration.\n");
896 static int cmd_dump(int argc, char *argv[]) {
897 bool only_reachable = false;
899 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
900 if(strcasecmp(argv[2], "nodes")) {
901 fprintf(stderr, "`reachable' only supported for nodes.\n");
905 only_reachable = true;
911 fprintf(stderr, "Invalid number of arguments.\n");
916 if(!connect_tincd(true))
921 if(!strcasecmp(argv[1], "nodes"))
922 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
923 else if(!strcasecmp(argv[1], "edges"))
924 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
925 else if(!strcasecmp(argv[1], "subnets"))
926 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
927 else if(!strcasecmp(argv[1], "connections"))
928 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
929 else if(!strcasecmp(argv[1], "graph")) {
930 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
931 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
933 } else if(!strcasecmp(argv[1], "digraph")) {
934 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
935 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
938 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
945 else if(do_graph == 2)
946 printf("digraph {\n");
948 while(recvline(fd, line, sizeof line)) {
949 char node1[4096], node2[4096];
950 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
952 if(do_graph && req == REQ_DUMP_NODES)
971 int cipher, digest, maclength, compression, distance, socket, weight;
972 short int pmtu, minmtu, maxmtu;
973 unsigned int options, status_int;
974 node_status_t status;
975 long int last_state_change;
978 case REQ_DUMP_NODES: {
979 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);
981 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
985 memcpy(&status, &status_int, sizeof status);
988 const char *color = "black";
989 if(!strcmp(host, "MYSELF"))
991 else if(!status.reachable)
993 else if(strcmp(via, node))
995 else if(!status.validkey)
999 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1001 if(only_reachable && !status.reachable)
1003 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",
1004 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1008 case REQ_DUMP_EDGES: {
1009 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1011 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1016 float w = 1 + 65536.0 / weight;
1017 if(do_graph == 1 && strcmp(node1, node2) > 0)
1018 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1019 else if(do_graph == 2)
1020 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1022 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1026 case REQ_DUMP_SUBNETS: {
1027 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1029 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1032 printf("%s owner %s\n", strip_weight(subnet), node);
1035 case REQ_DUMP_CONNECTIONS: {
1036 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1038 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1041 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1045 fprintf(stderr, "Unable to parse dump from tincd.\n");
1050 fprintf(stderr, "Error receiving dump.\n");
1054 static int cmd_purge(int argc, char *argv[]) {
1056 fprintf(stderr, "Too many arguments!\n");
1060 if(!connect_tincd(true))
1063 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1064 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1065 fprintf(stderr, "Could not purge old information.\n");
1072 static int cmd_debug(int argc, char *argv[]) {
1074 fprintf(stderr, "Invalid number of arguments.\n");
1078 if(!connect_tincd(true))
1081 int debuglevel = atoi(argv[1]);
1084 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1085 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1086 fprintf(stderr, "Could not set debug level.\n");
1090 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1094 static int cmd_retry(int argc, char *argv[]) {
1096 fprintf(stderr, "Too many arguments!\n");
1100 if(!connect_tincd(true))
1103 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1104 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1105 fprintf(stderr, "Could not retry outgoing connections.\n");
1112 static int cmd_connect(int argc, char *argv[]) {
1114 fprintf(stderr, "Invalid number of arguments.\n");
1118 if(!check_id(argv[1])) {
1119 fprintf(stderr, "Invalid name for node.\n");
1123 if(!connect_tincd(true))
1126 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1127 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1128 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1135 static int cmd_disconnect(int argc, char *argv[]) {
1137 fprintf(stderr, "Invalid number of arguments.\n");
1141 if(!check_id(argv[1])) {
1142 fprintf(stderr, "Invalid name for node.\n");
1146 if(!connect_tincd(true))
1149 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1150 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1151 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1158 static int cmd_top(int argc, char *argv[]) {
1160 fprintf(stderr, "Too many arguments!\n");
1165 if(!connect_tincd(true))
1171 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1176 static int cmd_pcap(int argc, char *argv[]) {
1178 fprintf(stderr, "Too many arguments!\n");
1182 if(!connect_tincd(true))
1185 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1190 static void sigint_handler(int sig) {
1191 fprintf(stderr, "\n");
1192 shutdown(fd, SHUT_RDWR);
1196 static int cmd_log(int argc, char *argv[]) {
1198 fprintf(stderr, "Too many arguments!\n");
1202 if(!connect_tincd(true))
1206 signal(SIGINT, sigint_handler);
1209 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1212 signal(SIGINT, SIG_DFL);
1220 static int cmd_pid(int argc, char *argv[]) {
1222 fprintf(stderr, "Too many arguments!\n");
1226 if(!connect_tincd(true) && !pid)
1229 printf("%d\n", pid);
1233 int rstrip(char *value) {
1234 int len = strlen(value);
1235 while(len && strchr("\t\r\n ", value[len - 1]))
1240 char *get_my_name(bool verbose) {
1241 FILE *f = fopen(tinc_conf, "r");
1244 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1250 while(fgets(buf, sizeof buf, f)) {
1251 int len = strcspn(buf, "\t =");
1253 value += strspn(value, "\t ");
1256 value += strspn(value, "\t ");
1261 if(strcasecmp(buf, "Name"))
1265 return strdup(value);
1271 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1275 const var_t variables[] = {
1276 /* Server configuration */
1277 {"AddressFamily", VAR_SERVER},
1278 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1279 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1280 {"BindToInterface", VAR_SERVER},
1281 {"Broadcast", VAR_SERVER | VAR_SAFE},
1282 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1283 {"DecrementTTL", VAR_SERVER},
1284 {"Device", VAR_SERVER},
1285 {"DeviceType", VAR_SERVER},
1286 {"DirectOnly", VAR_SERVER},
1287 {"ECDSAPrivateKeyFile", VAR_SERVER},
1288 {"ExperimentalProtocol", VAR_SERVER},
1289 {"Forwarding", VAR_SERVER},
1290 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1291 {"Hostnames", VAR_SERVER},
1292 {"IffOneQueue", VAR_SERVER},
1293 {"Interface", VAR_SERVER},
1294 {"KeyExpire", VAR_SERVER},
1295 {"LocalDiscovery", VAR_SERVER},
1296 {"MACExpire", VAR_SERVER},
1297 {"MaxConnectionBurst", VAR_SERVER},
1298 {"MaxOutputBufferSize", VAR_SERVER},
1299 {"MaxTimeout", VAR_SERVER},
1300 {"Mode", VAR_SERVER | VAR_SAFE},
1301 {"Name", VAR_SERVER},
1302 {"PingInterval", VAR_SERVER},
1303 {"PingTimeout", VAR_SERVER},
1304 {"PriorityInheritance", VAR_SERVER},
1305 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1306 {"PrivateKeyFile", VAR_SERVER},
1307 {"ProcessPriority", VAR_SERVER},
1308 {"Proxy", VAR_SERVER},
1309 {"ReplayWindow", VAR_SERVER},
1310 {"ScriptsExtension", VAR_SERVER},
1311 {"ScriptsInterpreter", VAR_SERVER},
1312 {"StrictSubnets", VAR_SERVER},
1313 {"TunnelServer", VAR_SERVER},
1314 {"UDPRcvBuf", VAR_SERVER},
1315 {"UDPSndBuf", VAR_SERVER},
1316 {"VDEGroup", VAR_SERVER},
1317 {"VDEPort", VAR_SERVER},
1318 /* Host configuration */
1319 {"Address", VAR_HOST | VAR_MULTIPLE},
1320 {"Cipher", VAR_SERVER | VAR_HOST},
1321 {"ClampMSS", VAR_SERVER | VAR_HOST},
1322 {"Compression", VAR_SERVER | VAR_HOST},
1323 {"Digest", VAR_SERVER | VAR_HOST},
1324 {"ECDSAPublicKey", VAR_HOST},
1325 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1326 {"IndirectData", VAR_SERVER | VAR_HOST},
1327 {"MACLength", VAR_SERVER | VAR_HOST},
1328 {"PMTU", VAR_SERVER | VAR_HOST},
1329 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1331 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1332 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1333 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1334 {"TCPOnly", VAR_SERVER | VAR_HOST},
1335 {"Weight", VAR_HOST | VAR_SAFE},
1339 static int cmd_config(int argc, char *argv[]) {
1341 fprintf(stderr, "Invalid number of arguments.\n");
1345 if(strcasecmp(argv[0], "config"))
1349 if(!strcasecmp(argv[1], "get")) {
1351 } else if(!strcasecmp(argv[1], "add")) {
1352 argv++, argc--, action = 1;
1353 } else if(!strcasecmp(argv[1], "del")) {
1354 argv++, argc--, action = -1;
1355 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1356 argv++, argc--, action = 0;
1360 fprintf(stderr, "Invalid number of arguments.\n");
1364 // Concatenate the rest of the command line
1365 strncpy(line, argv[1], sizeof line - 1);
1366 for(int i = 2; i < argc; i++) {
1367 strncat(line, " ", sizeof line - 1 - strlen(line));
1368 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1371 // Liberal parsing into node name, variable name and value.
1377 len = strcspn(line, "\t =");
1379 value += strspn(value, "\t ");
1382 value += strspn(value, "\t ");
1385 variable = strchr(line, '.');
1394 fprintf(stderr, "No variable given.\n");
1398 if(action >= 0 && !*value) {
1399 fprintf(stderr, "No value for variable given.\n");
1403 if(action < -1 && *value)
1406 /* Some simple checks. */
1408 bool warnonremove = false;
1410 for(int i = 0; variables[i].name; i++) {
1411 if(strcasecmp(variables[i].name, variable))
1415 variable = (char *)variables[i].name;
1417 /* Discourage use of obsolete variables. */
1419 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1421 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1423 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1428 /* Don't put server variables in host config files */
1430 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1432 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1434 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1439 /* Should this go into our own host config file? */
1441 if(!node && !(variables[i].type & VAR_SERVER)) {
1442 node = get_my_name(true);
1447 /* Change "add" into "set" for variables that do not allow multiple occurences.
1448 Turn on warnings when it seems variables might be removed unintentionally. */
1450 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1451 warnonremove = true;
1453 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1454 warnonremove = true;
1460 if(node && !check_id(node)) {
1461 fprintf(stderr, "Invalid name for node.\n");
1466 if(force || action < 0) {
1467 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1469 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1474 // Open the right configuration file.
1477 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1479 filename = tinc_conf;
1481 FILE *f = fopen(filename, "r");
1483 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1487 char *tmpfile = NULL;
1491 xasprintf(&tmpfile, "%s.config.tmp", filename);
1492 tf = fopen(tmpfile, "w");
1494 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1500 // Copy the file, making modifications on the fly, unless we are just getting a value.
1504 bool removed = false;
1507 while(fgets(buf1, sizeof buf1, f)) {
1508 buf1[sizeof buf1 - 1] = 0;
1509 strncpy(buf2, buf1, sizeof buf2);
1511 // Parse line in a simple way
1515 len = strcspn(buf2, "\t =");
1516 bvalue = buf2 + len;
1517 bvalue += strspn(bvalue, "\t ");
1518 if(*bvalue == '=') {
1520 bvalue += strspn(bvalue, "\t ");
1526 if(!strcasecmp(buf2, variable)) {
1530 printf("%s\n", bvalue);
1532 } else if(action == -1) {
1533 if(!*value || !strcasecmp(bvalue, value)) {
1538 } else if(action == 0) {
1539 // Warn if "set" was used for variables that can occur multiple times
1540 if(warnonremove && strcasecmp(bvalue, value))
1541 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1543 // Already set? Delete the rest...
1547 // Otherwise, replace.
1548 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1549 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1558 // Copy original line...
1559 if(fputs(buf1, tf) < 0) {
1560 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1564 // Add newline if it is missing...
1565 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1566 if(fputc('\n', tf) < 0) {
1567 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1574 // Make sure we read everything...
1575 if(ferror(f) || !feof(f)) {
1576 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1581 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1585 // Add new variable if necessary.
1586 if(action > 0 || (action == 0 && !set)) {
1587 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1588 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1595 fprintf(stderr, "No matching configuration variables found.\n");
1599 // Make sure we wrote everything...
1601 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1605 // Could we find what we had to remove?
1606 if(action < 0 && !removed) {
1608 fprintf(stderr, "No configuration variables deleted.\n");
1612 // Replace the configuration file with the new one
1614 if(remove(filename)) {
1615 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1619 if(rename(tmpfile, filename)) {
1620 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1624 // Silently try notifying a running tincd of changes.
1625 if(connect_tincd(false))
1626 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1631 bool check_id(const char *name) {
1635 for(int i = 0; i < strlen(name); i++) {
1636 if(!isalnum(name[i]) && name[i] != '_')
1643 static bool try_bind(int port) {
1644 struct addrinfo *ai = NULL;
1645 struct addrinfo hint = {
1646 .ai_flags = AI_PASSIVE,
1647 .ai_family = AF_UNSPEC,
1648 .ai_socktype = SOCK_STREAM,
1649 .ai_protocol = IPPROTO_TCP,
1653 snprintf(portstr, sizeof portstr, "%d", port);
1655 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1659 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1662 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1672 int check_port(char *name) {
1676 fprintf(stderr, "Warning: could not bind to port 655. ");
1678 for(int i = 0; i < 100; i++) {
1679 int port = 0x1000 + (rand() & 0x7fff);
1680 if(try_bind(port)) {
1682 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1683 FILE *f = fopen(filename, "a");
1686 fprintf(stderr, "Please change tinc's Port manually.\n");
1690 fprintf(f, "Port = %d\n", port);
1692 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1697 fprintf(stderr, "Please change tinc's Port manually.\n");
1701 static int cmd_init(int argc, char *argv[]) {
1702 if(!access(tinc_conf, F_OK)) {
1703 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1708 fprintf(stderr, "Too many arguments!\n");
1710 } else if(argc < 2) {
1713 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1715 if(!fgets(buf, sizeof buf, stdin)) {
1716 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1719 int len = rstrip(buf);
1721 fprintf(stderr, "No name given!\n");
1726 fprintf(stderr, "No Name given!\n");
1730 name = strdup(argv[1]);
1732 fprintf(stderr, "No Name given!\n");
1737 if(!check_id(name)) {
1738 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1742 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1743 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1747 if(mkdir(confbase, 0777) && errno != EEXIST) {
1748 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1752 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1753 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1757 FILE *f = fopen(tinc_conf, "w");
1759 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1763 fprintf(f, "Name = %s\n", name);
1766 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1773 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1774 if(access(filename, F_OK)) {
1775 FILE *f = fopenmask(filename, "w", 0777);
1777 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1780 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");
1789 static int cmd_generate_keys(int argc, char *argv[]) {
1791 fprintf(stderr, "Too many arguments!\n");
1796 name = get_my_name(false);
1798 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1801 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1803 fprintf(stderr, "Too many arguments!\n");
1808 name = get_my_name(false);
1810 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1813 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1815 fprintf(stderr, "Too many arguments!\n");
1820 name = get_my_name(false);
1822 return !ecdsa_keygen(true);
1825 static int cmd_help(int argc, char *argv[]) {
1830 static int cmd_version(int argc, char *argv[]) {
1832 fprintf(stderr, "Too many arguments!\n");
1840 static int cmd_info(int argc, char *argv[]) {
1842 fprintf(stderr, "Invalid number of arguments.\n");
1846 if(!connect_tincd(true))
1849 return info(fd, argv[1]);
1852 static const char *conffiles[] = {
1863 static int cmd_edit(int argc, char *argv[]) {
1865 fprintf(stderr, "Invalid number of arguments.\n");
1869 char *filename = NULL;
1871 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1872 for(int i = 0; conffiles[i]; i++) {
1873 if(!strcmp(argv[1], conffiles[i])) {
1874 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1883 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1884 char *dash = strchr(argv[1], '-');
1887 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1888 fprintf(stderr, "Invalid configuration filename.\n");
1896 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1898 xasprintf(&command, "edit \"%s\"", filename);
1900 int result = system(command);
1904 // Silently try notifying a running tincd of changes.
1905 if(connect_tincd(false))
1906 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1911 static int export(const char *name, FILE *out) {
1913 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1914 FILE *in = fopen(filename, "r");
1916 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1920 fprintf(out, "Name = %s\n", name);
1922 while(fgets(buf, sizeof buf, in)) {
1923 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1928 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1937 static int cmd_export(int argc, char *argv[]) {
1939 fprintf(stderr, "Too many arguments!\n");
1943 char *name = get_my_name(true);
1947 int result = export(name, stdout);
1955 static int cmd_export_all(int argc, char *argv[]) {
1957 fprintf(stderr, "Too many arguments!\n");
1961 DIR *dir = opendir(hosts_dir);
1963 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1971 while((ent = readdir(dir))) {
1972 if(!check_id(ent->d_name))
1978 printf("#---------------------------------------------------------------#\n");
1980 result |= export(ent->d_name, stdout);
1989 static int cmd_import(int argc, char *argv[]) {
1991 fprintf(stderr, "Too many arguments!\n");
2000 char *filename = NULL;
2002 bool firstline = true;
2004 while(fgets(buf, sizeof buf, in)) {
2005 if(sscanf(buf, "Name = %s", name) == 1) {
2008 if(!check_id(name)) {
2009 fprintf(stderr, "Invalid Name in input!\n");
2017 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2019 if(!force && !access(filename, F_OK)) {
2020 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2025 out = fopen(filename, "w");
2027 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2033 } else if(firstline) {
2034 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2039 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2043 if(fputs(buf, out) < 0) {
2044 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2054 fprintf(stderr, "Imported %d host configuration files.\n", count);
2057 fprintf(stderr, "No host configuration files imported.\n");
2062 static int cmd_exchange(int argc, char *argv[]) {
2063 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2066 static int cmd_exchange_all(int argc, char *argv[]) {
2067 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2070 static const struct {
2071 const char *command;
2072 int (*function)(int argc, char *argv[]);
2075 {"start", cmd_start},
2077 {"restart", cmd_restart},
2078 {"reload", cmd_reload},
2080 {"purge", cmd_purge},
2081 {"debug", cmd_debug},
2082 {"retry", cmd_retry},
2083 {"connect", cmd_connect},
2084 {"disconnect", cmd_disconnect},
2089 {"config", cmd_config, true},
2090 {"add", cmd_config},
2091 {"del", cmd_config},
2092 {"get", cmd_config},
2093 {"set", cmd_config},
2095 {"generate-keys", cmd_generate_keys},
2096 {"generate-rsa-keys", cmd_generate_rsa_keys},
2097 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2099 {"version", cmd_version},
2102 {"export", cmd_export},
2103 {"export-all", cmd_export_all},
2104 {"import", cmd_import},
2105 {"exchange", cmd_exchange},
2106 {"exchange-all", cmd_exchange_all},
2107 {"invite", cmd_invite},
2112 #ifdef HAVE_READLINE
2113 static char *complete_command(const char *text, int state) {
2121 while(commands[i].command) {
2122 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2123 return xstrdup(commands[i].command);
2130 static char *complete_dump(const char *text, int state) {
2131 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2140 if(!strncasecmp(matches[i], text, strlen(text)))
2141 return xstrdup(matches[i]);
2148 static char *complete_config(const char *text, int state) {
2156 while(variables[i].name) {
2157 char *dot = strchr(text, '.');
2159 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2161 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2165 if(!strncasecmp(variables[i].name, text, strlen(text)))
2166 return xstrdup(variables[i].name);
2174 static char *complete_info(const char *text, int state) {
2178 if(!connect_tincd(false))
2180 // Check the list of nodes
2181 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2182 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2185 while(recvline(fd, line, sizeof line)) {
2187 int n = sscanf(line, "%d %d %s", &code, &req, item);
2197 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2201 if(!strncmp(item, text, strlen(text)))
2202 return xstrdup(strip_weight(item));
2208 static char *complete_nothing(const char *text, int state) {
2212 static char **completion (const char *text, int start, int end) {
2213 char **matches = NULL;
2216 matches = rl_completion_matches(text, complete_command);
2217 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2218 matches = rl_completion_matches(text, complete_dump);
2219 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2220 matches = rl_completion_matches(text, complete_config);
2221 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2222 matches = rl_completion_matches(text, complete_config);
2223 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2224 matches = rl_completion_matches(text, complete_config);
2225 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2226 matches = rl_completion_matches(text, complete_config);
2227 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2228 matches = rl_completion_matches(text, complete_info);
2234 static int cmd_shell(int argc, char *argv[]) {
2236 xasprintf(&prompt, "%s> ", identname);
2240 int maxargs = argc + 16;
2241 char **nargv = xmalloc(maxargs * sizeof *nargv);
2243 for(int i = 0; i < argc; i++)
2246 #ifdef HAVE_READLINE
2247 rl_readline_name = "tinc";
2248 rl_completion_entry_function = complete_nothing;
2249 rl_attempted_completion_function = completion;
2250 rl_filename_completion_desired = 0;
2255 #ifdef HAVE_READLINE
2259 rl_basic_word_break_characters = "\t\n ";
2260 line = readline(prompt);
2262 copy = xstrdup(line);
2264 line = fgets(buf, sizeof buf, stdin);
2268 fputs(prompt, stdout);
2270 line = fgets(buf, sizeof buf, stdin);
2276 /* Ignore comments */
2284 char *p = line + strspn(line, " \t\n");
2285 char *next = strtok(p, " \t\n");
2288 if(nargc >= maxargs) {
2289 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2292 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2297 next = strtok(NULL, " \t\n");
2303 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2308 for(int i = 0; commands[i].command; i++) {
2309 if(!strcasecmp(nargv[argc], commands[i].command)) {
2310 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2316 #ifdef HAVE_READLINE
2322 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2335 int main(int argc, char *argv[]) {
2336 program_name = argv[0];
2340 if(!parse_options(argc, argv))
2344 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2345 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2358 static struct WSAData wsa_state;
2360 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2361 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2369 tty = isatty(0) && isatty(1);
2372 return cmd_shell(argc, argv);
2374 for(int i = 0; commands[i].command; i++) {
2375 if(!strcasecmp(argv[optind], commands[i].command))
2376 return commands[i].function(argc - optind, argv + optind);
2379 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);