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 /* Open a file with the desired permissions, minus the umask.
215 Also, if we want to create an executable file, we call fchmod()
216 to set the executable bits. */
218 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
219 mode_t mask = umask(0);
222 FILE *f = fopen(filename, mode);
224 if((perms & 0444) && f)
225 fchmod(fileno(f), perms);
231 static void disable_old_keys(const char *filename, const char *what) {
232 char tmpfile[PATH_MAX] = "";
234 bool disabled = false;
239 r = fopen(filename, "r");
243 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
245 struct stat st = {.st_mode = 0600};
246 fstat(fileno(r), &st);
247 w = fopenmask(tmpfile, "w", st.st_mode);
249 while(fgets(buf, sizeof buf, r)) {
250 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
251 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
257 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
263 if(block || ecdsapubkey)
265 if(fputs(buf, w) < 0) {
271 if(block && !strncmp(buf, "-----END ", 9))
278 if(ferror(r) || fclose(r) < 0)
283 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
290 // We cannot atomically replace files on Windows.
291 char bakfile[PATH_MAX] = "";
292 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
293 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
294 rename(bakfile, filename);
296 if(rename(tmpfile, filename)) {
298 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
303 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
310 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
316 /* Check stdin and stdout */
318 /* Ask for a file and/or directory name. */
319 fprintf(stdout, "Please enter a file to save %s to [%s]: ", what, filename);
322 if(fgets(buf, sizeof buf, stdin) == NULL) {
323 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
327 size_t len = strlen(buf);
336 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
338 if(filename[0] != '/') {
340 /* The directory is a relative path or a filename. */
341 directory = get_current_dir_name();
342 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
346 disable_old_keys(filename, what);
348 /* Open it first to keep the inode busy */
350 r = fopenmask(filename, mode, perms);
353 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
361 Generate a public/private ECDSA keypair, and ask for a file to store
364 static bool ecdsa_keygen(bool ask) {
367 char *pubname, *privname;
369 fprintf(stderr, "Generating ECDSA keypair:\n");
371 if(!(key = ecdsa_generate())) {
372 fprintf(stderr, "Error during key generation!\n");
375 fprintf(stderr, "Done.\n");
377 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
378 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
384 if(!ecdsa_write_pem_private_key(key, f)) {
385 fprintf(stderr, "Error writing private key!\n");
394 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
396 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
398 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
404 char *pubkey = ecdsa_get_base64_public_key(key);
405 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
415 Generate a public/private RSA keypair, and ask for a file to store
418 static bool rsa_keygen(int bits, bool ask) {
421 char *pubname, *privname;
423 fprintf(stderr, "Generating %d bits keys:\n", bits);
425 if(!(key = rsa_generate(bits, 0x10001))) {
426 fprintf(stderr, "Error during key generation!\n");
429 fprintf(stderr, "Done.\n");
431 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
432 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
438 if(!rsa_write_pem_private_key(key, f)) {
439 fprintf(stderr, "Error writing private key!\n");
448 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
450 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
452 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
458 if(!rsa_write_pem_public_key(key, f)) {
459 fprintf(stderr, "Error writing public key!\n");
474 bool recvline(int fd, char *line, size_t len) {
475 char *newline = NULL;
480 while(!(newline = memchr(buffer, '\n', blen))) {
481 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
482 if(result == -1 && errno == EINTR)
489 if(newline - buffer >= len)
492 len = newline - buffer;
494 memcpy(line, buffer, len);
496 memmove(buffer, newline + 1, blen - len - 1);
502 bool recvdata(int fd, char *data, size_t len) {
507 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
508 if(result == -1 && errno == EINTR)
515 memcpy(data, buffer, len);
516 memmove(buffer, buffer + len, blen - len);
522 bool sendline(int fd, char *format, ...) {
523 static char buffer[4096];
528 va_start(ap, format);
529 blen = vsnprintf(buffer, sizeof buffer, format, ap);
532 if(blen < 1 || blen >= sizeof buffer)
539 int result = send(fd, p, blen, 0);
540 if(result == -1 && errno == EINTR)
551 static void pcap(int fd, FILE *out, int snaplen) {
552 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
560 uint32_t tz_accuracy;
567 snaplen ?: sizeof data,
580 fwrite(&header, sizeof header, 1, out);
584 while(recvline(fd, line, sizeof line)) {
586 int n = sscanf(line, "%d %d %d", &code, &req, &len);
587 gettimeofday(&tv, NULL);
588 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
590 if(!recvdata(fd, data, len))
592 packet.tv_sec = tv.tv_sec;
593 packet.tv_usec = tv.tv_usec;
595 packet.origlen = len;
596 fwrite(&packet, sizeof packet, 1, out);
597 fwrite(data, len, 1, out);
602 static void logcontrol(int fd, FILE *out, int level) {
603 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
607 while(recvline(fd, line, sizeof line)) {
609 int n = sscanf(line, "%d %d %d", &code, &req, &len);
610 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
612 if(!recvdata(fd, data, len))
614 fwrite(data, len, 1, out);
621 static bool remove_service(void) {
622 SC_HANDLE manager = NULL;
623 SC_HANDLE service = NULL;
624 SERVICE_STATUS status = {0};
626 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
628 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
632 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
635 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
639 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
640 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
642 fprintf(stderr, "%s service stopped\n", identname);
644 if(!DeleteService(service)) {
645 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
649 fprintf(stderr, "%s service removed\n", identname);
655 bool connect_tincd(bool verbose) {
660 struct timeval tv = {0, 0};
661 if(select(fd + 1, &r, NULL, NULL, &tv)) {
662 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
670 FILE *f = fopen(pidfilename, "r");
673 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
680 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
682 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
690 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
692 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
698 struct sockaddr_un sa;
699 sa.sun_family = AF_UNIX;
700 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
702 fd = socket(AF_UNIX, SOCK_STREAM, 0);
705 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
709 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
711 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
717 struct addrinfo hints = {
718 .ai_family = AF_UNSPEC,
719 .ai_socktype = SOCK_STREAM,
720 .ai_protocol = IPPROTO_TCP,
724 struct addrinfo *res = NULL;
726 if(getaddrinfo(host, port, &hints, &res) || !res) {
728 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
732 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
735 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
740 unsigned long arg = 0;
742 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
744 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
748 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
750 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
762 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
764 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
770 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
772 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
774 fprintf(stderr, "Could not fully establish control socket connection\n");
784 static int cmd_start(int argc, char *argv[]) {
785 if(connect_tincd(false)) {
787 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
789 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
794 char *slash = strrchr(program_name, '/');
797 if ((c = strrchr(program_name, '\\')) > slash)
802 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
807 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
810 for(int i = 1; i < optind; i++)
811 nargv[nargc++] = orig_argv[i];
812 for(int i = 1; i < argc; i++)
813 nargv[nargc++] = argv[i];
817 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
822 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
828 exit(execvp(c, nargv));
832 int status = -1, result;
834 signal(SIGINT, SIG_IGN);
836 result = waitpid(pid, &status, 0);
838 signal(SIGINT, SIG_DFL);
841 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
842 fprintf(stderr, "Error starting %s\n", c);
850 static int cmd_stop(int argc, char *argv[]) {
852 fprintf(stderr, "Too many arguments!\n");
857 if(!connect_tincd(true)) {
859 if(kill(pid, SIGTERM)) {
860 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
864 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
865 waitpid(pid, NULL, 0);
872 sendline(fd, "%d %d", CONTROL, REQ_STOP);
874 while(recvline(fd, line, sizeof line)) {
875 // Wait for tincd to close the connection...
878 if(!remove_service())
888 static int cmd_restart(int argc, char *argv[]) {
890 return cmd_start(argc, argv);
893 static int cmd_reload(int argc, char *argv[]) {
895 fprintf(stderr, "Too many arguments!\n");
899 if(!connect_tincd(true))
902 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
903 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
904 fprintf(stderr, "Could not reload configuration.\n");
912 static int cmd_dump(int argc, char *argv[]) {
913 bool only_reachable = false;
915 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
916 if(strcasecmp(argv[2], "nodes")) {
917 fprintf(stderr, "`reachable' only supported for nodes.\n");
921 only_reachable = true;
927 fprintf(stderr, "Invalid number of arguments.\n");
932 if(!connect_tincd(true))
937 if(!strcasecmp(argv[1], "nodes"))
938 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
939 else if(!strcasecmp(argv[1], "edges"))
940 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
941 else if(!strcasecmp(argv[1], "subnets"))
942 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
943 else if(!strcasecmp(argv[1], "connections"))
944 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
945 else if(!strcasecmp(argv[1], "graph")) {
946 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
947 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
949 } else if(!strcasecmp(argv[1], "digraph")) {
950 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
951 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
954 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
961 else if(do_graph == 2)
962 printf("digraph {\n");
964 while(recvline(fd, line, sizeof line)) {
965 char node1[4096], node2[4096];
966 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
968 if(do_graph && req == REQ_DUMP_NODES)
987 int cipher, digest, maclength, compression, distance, socket, weight;
988 short int pmtu, minmtu, maxmtu;
989 unsigned int options, status_int;
990 node_status_t status;
991 long int last_state_change;
994 case REQ_DUMP_NODES: {
995 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);
997 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1001 memcpy(&status, &status_int, sizeof status);
1004 const char *color = "black";
1005 if(!strcmp(host, "MYSELF"))
1007 else if(!status.reachable)
1009 else if(strcmp(via, node))
1011 else if(!status.validkey)
1015 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1017 if(only_reachable && !status.reachable)
1019 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",
1020 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1024 case REQ_DUMP_EDGES: {
1025 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1027 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1032 float w = 1 + 65536.0 / weight;
1033 if(do_graph == 1 && strcmp(node1, node2) > 0)
1034 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1035 else if(do_graph == 2)
1036 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1038 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1042 case REQ_DUMP_SUBNETS: {
1043 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1045 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1048 printf("%s owner %s\n", strip_weight(subnet), node);
1051 case REQ_DUMP_CONNECTIONS: {
1052 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1054 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1057 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1061 fprintf(stderr, "Unable to parse dump from tincd.\n");
1066 fprintf(stderr, "Error receiving dump.\n");
1070 static int cmd_purge(int argc, char *argv[]) {
1072 fprintf(stderr, "Too many arguments!\n");
1076 if(!connect_tincd(true))
1079 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1080 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1081 fprintf(stderr, "Could not purge old information.\n");
1088 static int cmd_debug(int argc, char *argv[]) {
1090 fprintf(stderr, "Invalid number of arguments.\n");
1094 if(!connect_tincd(true))
1097 int debuglevel = atoi(argv[1]);
1100 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1101 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1102 fprintf(stderr, "Could not set debug level.\n");
1106 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1110 static int cmd_retry(int argc, char *argv[]) {
1112 fprintf(stderr, "Too many arguments!\n");
1116 if(!connect_tincd(true))
1119 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1120 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1121 fprintf(stderr, "Could not retry outgoing connections.\n");
1128 static int cmd_connect(int argc, char *argv[]) {
1130 fprintf(stderr, "Invalid number of arguments.\n");
1134 if(!check_id(argv[1])) {
1135 fprintf(stderr, "Invalid name for node.\n");
1139 if(!connect_tincd(true))
1142 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1143 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1144 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1151 static int cmd_disconnect(int argc, char *argv[]) {
1153 fprintf(stderr, "Invalid number of arguments.\n");
1157 if(!check_id(argv[1])) {
1158 fprintf(stderr, "Invalid name for node.\n");
1162 if(!connect_tincd(true))
1165 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1166 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1167 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1174 static int cmd_top(int argc, char *argv[]) {
1176 fprintf(stderr, "Too many arguments!\n");
1181 if(!connect_tincd(true))
1187 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1192 static int cmd_pcap(int argc, char *argv[]) {
1194 fprintf(stderr, "Too many arguments!\n");
1198 if(!connect_tincd(true))
1201 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1206 static void sigint_handler(int sig) {
1207 fprintf(stderr, "\n");
1208 shutdown(fd, SHUT_RDWR);
1212 static int cmd_log(int argc, char *argv[]) {
1214 fprintf(stderr, "Too many arguments!\n");
1218 if(!connect_tincd(true))
1222 signal(SIGINT, sigint_handler);
1225 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1228 signal(SIGINT, SIG_DFL);
1236 static int cmd_pid(int argc, char *argv[]) {
1238 fprintf(stderr, "Too many arguments!\n");
1242 if(!connect_tincd(true) && !pid)
1245 printf("%d\n", pid);
1249 int rstrip(char *value) {
1250 int len = strlen(value);
1251 while(len && strchr("\t\r\n ", value[len - 1]))
1256 char *get_my_name(bool verbose) {
1257 FILE *f = fopen(tinc_conf, "r");
1260 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1266 while(fgets(buf, sizeof buf, f)) {
1267 int len = strcspn(buf, "\t =");
1269 value += strspn(value, "\t ");
1272 value += strspn(value, "\t ");
1277 if(strcasecmp(buf, "Name"))
1281 return strdup(value);
1287 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1291 const var_t variables[] = {
1292 /* Server configuration */
1293 {"AddressFamily", VAR_SERVER},
1294 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1295 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1296 {"BindToInterface", VAR_SERVER},
1297 {"Broadcast", VAR_SERVER | VAR_SAFE},
1298 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1299 {"DecrementTTL", VAR_SERVER},
1300 {"Device", VAR_SERVER},
1301 {"DeviceType", VAR_SERVER},
1302 {"DirectOnly", VAR_SERVER},
1303 {"ECDSAPrivateKeyFile", VAR_SERVER},
1304 {"ExperimentalProtocol", VAR_SERVER},
1305 {"Forwarding", VAR_SERVER},
1306 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1307 {"Hostnames", VAR_SERVER},
1308 {"IffOneQueue", VAR_SERVER},
1309 {"Interface", VAR_SERVER},
1310 {"KeyExpire", VAR_SERVER},
1311 {"LocalDiscovery", VAR_SERVER},
1312 {"MACExpire", VAR_SERVER},
1313 {"MaxConnectionBurst", VAR_SERVER},
1314 {"MaxOutputBufferSize", VAR_SERVER},
1315 {"MaxTimeout", VAR_SERVER},
1316 {"Mode", VAR_SERVER | VAR_SAFE},
1317 {"Name", VAR_SERVER},
1318 {"PingInterval", VAR_SERVER},
1319 {"PingTimeout", VAR_SERVER},
1320 {"PriorityInheritance", VAR_SERVER},
1321 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1322 {"PrivateKeyFile", VAR_SERVER},
1323 {"ProcessPriority", VAR_SERVER},
1324 {"Proxy", VAR_SERVER},
1325 {"ReplayWindow", VAR_SERVER},
1326 {"ScriptsExtension", VAR_SERVER},
1327 {"ScriptsInterpreter", VAR_SERVER},
1328 {"StrictSubnets", VAR_SERVER},
1329 {"TunnelServer", VAR_SERVER},
1330 {"UDPRcvBuf", VAR_SERVER},
1331 {"UDPSndBuf", VAR_SERVER},
1332 {"VDEGroup", VAR_SERVER},
1333 {"VDEPort", VAR_SERVER},
1334 /* Host configuration */
1335 {"Address", VAR_HOST | VAR_MULTIPLE},
1336 {"Cipher", VAR_SERVER | VAR_HOST},
1337 {"ClampMSS", VAR_SERVER | VAR_HOST},
1338 {"Compression", VAR_SERVER | VAR_HOST},
1339 {"Digest", VAR_SERVER | VAR_HOST},
1340 {"ECDSAPublicKey", VAR_HOST},
1341 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1342 {"IndirectData", VAR_SERVER | VAR_HOST},
1343 {"MACLength", VAR_SERVER | VAR_HOST},
1344 {"PMTU", VAR_SERVER | VAR_HOST},
1345 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1347 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1348 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1349 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1350 {"TCPOnly", VAR_SERVER | VAR_HOST},
1351 {"Weight", VAR_HOST | VAR_SAFE},
1355 static int cmd_config(int argc, char *argv[]) {
1357 fprintf(stderr, "Invalid number of arguments.\n");
1361 if(strcasecmp(argv[0], "config"))
1365 if(!strcasecmp(argv[1], "get")) {
1367 } else if(!strcasecmp(argv[1], "add")) {
1368 argv++, argc--, action = 1;
1369 } else if(!strcasecmp(argv[1], "del")) {
1370 argv++, argc--, action = -1;
1371 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1372 argv++, argc--, action = 0;
1376 fprintf(stderr, "Invalid number of arguments.\n");
1380 // Concatenate the rest of the command line
1381 strncpy(line, argv[1], sizeof line - 1);
1382 for(int i = 2; i < argc; i++) {
1383 strncat(line, " ", sizeof line - 1 - strlen(line));
1384 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1387 // Liberal parsing into node name, variable name and value.
1393 len = strcspn(line, "\t =");
1395 value += strspn(value, "\t ");
1398 value += strspn(value, "\t ");
1401 variable = strchr(line, '.');
1410 fprintf(stderr, "No variable given.\n");
1414 if(action >= 0 && !*value) {
1415 fprintf(stderr, "No value for variable given.\n");
1419 if(action < -1 && *value)
1422 /* Some simple checks. */
1424 bool warnonremove = false;
1426 for(int i = 0; variables[i].name; i++) {
1427 if(strcasecmp(variables[i].name, variable))
1431 variable = (char *)variables[i].name;
1433 /* Discourage use of obsolete variables. */
1435 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1437 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1439 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1444 /* Don't put server variables in host config files */
1446 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1448 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1450 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1455 /* Should this go into our own host config file? */
1457 if(!node && !(variables[i].type & VAR_SERVER)) {
1458 node = get_my_name(true);
1463 /* Change "add" into "set" for variables that do not allow multiple occurences.
1464 Turn on warnings when it seems variables might be removed unintentionally. */
1466 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1467 warnonremove = true;
1469 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1470 warnonremove = true;
1476 if(node && !check_id(node)) {
1477 fprintf(stderr, "Invalid name for node.\n");
1482 if(force || action < 0) {
1483 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1485 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1490 // Open the right configuration file.
1493 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1495 filename = tinc_conf;
1497 FILE *f = fopen(filename, "r");
1499 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1503 char *tmpfile = NULL;
1507 xasprintf(&tmpfile, "%s.config.tmp", filename);
1508 tf = fopen(tmpfile, "w");
1510 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1516 // Copy the file, making modifications on the fly, unless we are just getting a value.
1520 bool removed = false;
1523 while(fgets(buf1, sizeof buf1, f)) {
1524 buf1[sizeof buf1 - 1] = 0;
1525 strncpy(buf2, buf1, sizeof buf2);
1527 // Parse line in a simple way
1531 len = strcspn(buf2, "\t =");
1532 bvalue = buf2 + len;
1533 bvalue += strspn(bvalue, "\t ");
1534 if(*bvalue == '=') {
1536 bvalue += strspn(bvalue, "\t ");
1542 if(!strcasecmp(buf2, variable)) {
1546 printf("%s\n", bvalue);
1548 } else if(action == -1) {
1549 if(!*value || !strcasecmp(bvalue, value)) {
1554 } else if(action == 0) {
1555 // Warn if "set" was used for variables that can occur multiple times
1556 if(warnonremove && strcasecmp(bvalue, value))
1557 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1559 // Already set? Delete the rest...
1563 // Otherwise, replace.
1564 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1565 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1574 // Copy original line...
1575 if(fputs(buf1, tf) < 0) {
1576 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1580 // Add newline if it is missing...
1581 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1582 if(fputc('\n', tf) < 0) {
1583 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1590 // Make sure we read everything...
1591 if(ferror(f) || !feof(f)) {
1592 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1597 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1601 // Add new variable if necessary.
1602 if(action > 0 || (action == 0 && !set)) {
1603 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1604 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1611 fprintf(stderr, "No matching configuration variables found.\n");
1615 // Make sure we wrote everything...
1617 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1621 // Could we find what we had to remove?
1622 if(action < 0 && !removed) {
1624 fprintf(stderr, "No configuration variables deleted.\n");
1628 // Replace the configuration file with the new one
1630 if(remove(filename)) {
1631 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1635 if(rename(tmpfile, filename)) {
1636 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1640 // Silently try notifying a running tincd of changes.
1641 if(connect_tincd(false))
1642 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1647 bool check_id(const char *name) {
1651 for(int i = 0; i < strlen(name); i++) {
1652 if(!isalnum(name[i]) && name[i] != '_')
1659 static bool try_bind(int port) {
1660 struct addrinfo *ai = NULL;
1661 struct addrinfo hint = {
1662 .ai_flags = AI_PASSIVE,
1663 .ai_family = AF_UNSPEC,
1664 .ai_socktype = SOCK_STREAM,
1665 .ai_protocol = IPPROTO_TCP,
1669 snprintf(portstr, sizeof portstr, "%d", port);
1671 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1675 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1678 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1688 int check_port(char *name) {
1692 fprintf(stderr, "Warning: could not bind to port 655. ");
1694 for(int i = 0; i < 100; i++) {
1695 int port = 0x1000 + (rand() & 0x7fff);
1696 if(try_bind(port)) {
1698 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1699 FILE *f = fopen(filename, "a");
1702 fprintf(stderr, "Please change tinc's Port manually.\n");
1706 fprintf(f, "Port = %d\n", port);
1708 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1713 fprintf(stderr, "Please change tinc's Port manually.\n");
1717 static int cmd_init(int argc, char *argv[]) {
1718 if(!access(tinc_conf, F_OK)) {
1719 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1724 fprintf(stderr, "Too many arguments!\n");
1726 } else if(argc < 2) {
1729 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1731 if(!fgets(buf, sizeof buf, stdin)) {
1732 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1735 int len = rstrip(buf);
1737 fprintf(stderr, "No name given!\n");
1742 fprintf(stderr, "No Name given!\n");
1746 name = strdup(argv[1]);
1748 fprintf(stderr, "No Name given!\n");
1753 if(!check_id(name)) {
1754 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1758 if(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
1759 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1763 if(mkdir(confbase, 0777) && errno != EEXIST) {
1764 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1768 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1769 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1773 FILE *f = fopen(tinc_conf, "w");
1775 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1779 fprintf(f, "Name = %s\n", name);
1782 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1789 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1790 if(access(filename, F_OK)) {
1791 FILE *f = fopenmask(filename, "w", 0777);
1793 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1796 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");
1805 static int cmd_generate_keys(int argc, char *argv[]) {
1807 fprintf(stderr, "Too many arguments!\n");
1812 name = get_my_name(false);
1814 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1817 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1819 fprintf(stderr, "Too many arguments!\n");
1824 name = get_my_name(false);
1826 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1829 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1831 fprintf(stderr, "Too many arguments!\n");
1836 name = get_my_name(false);
1838 return !ecdsa_keygen(true);
1841 static int cmd_help(int argc, char *argv[]) {
1846 static int cmd_version(int argc, char *argv[]) {
1848 fprintf(stderr, "Too many arguments!\n");
1856 static int cmd_info(int argc, char *argv[]) {
1858 fprintf(stderr, "Invalid number of arguments.\n");
1862 if(!connect_tincd(true))
1865 return info(fd, argv[1]);
1868 static const char *conffiles[] = {
1879 static int cmd_edit(int argc, char *argv[]) {
1881 fprintf(stderr, "Invalid number of arguments.\n");
1885 char *filename = NULL;
1887 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1888 for(int i = 0; conffiles[i]; i++) {
1889 if(!strcmp(argv[1], conffiles[i])) {
1890 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1899 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1900 char *dash = strchr(argv[1], '-');
1903 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1904 fprintf(stderr, "Invalid configuration filename.\n");
1912 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1914 xasprintf(&command, "edit \"%s\"", filename);
1916 int result = system(command);
1920 // Silently try notifying a running tincd of changes.
1921 if(connect_tincd(false))
1922 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1927 static int export(const char *name, FILE *out) {
1929 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1930 FILE *in = fopen(filename, "r");
1932 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1936 fprintf(out, "Name = %s\n", name);
1938 while(fgets(buf, sizeof buf, in)) {
1939 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1944 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1953 static int cmd_export(int argc, char *argv[]) {
1955 fprintf(stderr, "Too many arguments!\n");
1959 char *name = get_my_name(true);
1963 int result = export(name, stdout);
1971 static int cmd_export_all(int argc, char *argv[]) {
1973 fprintf(stderr, "Too many arguments!\n");
1977 DIR *dir = opendir(hosts_dir);
1979 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1987 while((ent = readdir(dir))) {
1988 if(!check_id(ent->d_name))
1994 printf("#---------------------------------------------------------------#\n");
1996 result |= export(ent->d_name, stdout);
2005 static int cmd_import(int argc, char *argv[]) {
2007 fprintf(stderr, "Too many arguments!\n");
2016 char *filename = NULL;
2018 bool firstline = true;
2020 while(fgets(buf, sizeof buf, in)) {
2021 if(sscanf(buf, "Name = %s", name) == 1) {
2024 if(!check_id(name)) {
2025 fprintf(stderr, "Invalid Name in input!\n");
2033 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2035 if(!force && !access(filename, F_OK)) {
2036 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2041 out = fopen(filename, "w");
2043 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2049 } else if(firstline) {
2050 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2055 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2059 if(fputs(buf, out) < 0) {
2060 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2070 fprintf(stderr, "Imported %d host configuration files.\n", count);
2073 fprintf(stderr, "No host configuration files imported.\n");
2078 static int cmd_exchange(int argc, char *argv[]) {
2079 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2082 static int cmd_exchange_all(int argc, char *argv[]) {
2083 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2086 static const struct {
2087 const char *command;
2088 int (*function)(int argc, char *argv[]);
2091 {"start", cmd_start},
2093 {"restart", cmd_restart},
2094 {"reload", cmd_reload},
2096 {"purge", cmd_purge},
2097 {"debug", cmd_debug},
2098 {"retry", cmd_retry},
2099 {"connect", cmd_connect},
2100 {"disconnect", cmd_disconnect},
2105 {"config", cmd_config, true},
2106 {"add", cmd_config},
2107 {"del", cmd_config},
2108 {"get", cmd_config},
2109 {"set", cmd_config},
2111 {"generate-keys", cmd_generate_keys},
2112 {"generate-rsa-keys", cmd_generate_rsa_keys},
2113 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2115 {"version", cmd_version},
2118 {"export", cmd_export},
2119 {"export-all", cmd_export_all},
2120 {"import", cmd_import},
2121 {"exchange", cmd_exchange},
2122 {"exchange-all", cmd_exchange_all},
2123 {"invite", cmd_invite},
2128 #ifdef HAVE_READLINE
2129 static char *complete_command(const char *text, int state) {
2137 while(commands[i].command) {
2138 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2139 return xstrdup(commands[i].command);
2146 static char *complete_dump(const char *text, int state) {
2147 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2156 if(!strncasecmp(matches[i], text, strlen(text)))
2157 return xstrdup(matches[i]);
2164 static char *complete_config(const char *text, int state) {
2172 while(variables[i].name) {
2173 char *dot = strchr(text, '.');
2175 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2177 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2181 if(!strncasecmp(variables[i].name, text, strlen(text)))
2182 return xstrdup(variables[i].name);
2190 static char *complete_info(const char *text, int state) {
2194 if(!connect_tincd(false))
2196 // Check the list of nodes
2197 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2198 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2201 while(recvline(fd, line, sizeof line)) {
2203 int n = sscanf(line, "%d %d %s", &code, &req, item);
2213 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2217 if(!strncmp(item, text, strlen(text)))
2218 return xstrdup(strip_weight(item));
2224 static char *complete_nothing(const char *text, int state) {
2228 static char **completion (const char *text, int start, int end) {
2229 char **matches = NULL;
2232 matches = rl_completion_matches(text, complete_command);
2233 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2234 matches = rl_completion_matches(text, complete_dump);
2235 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2236 matches = rl_completion_matches(text, complete_config);
2237 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2238 matches = rl_completion_matches(text, complete_config);
2239 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2240 matches = rl_completion_matches(text, complete_config);
2241 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2242 matches = rl_completion_matches(text, complete_config);
2243 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2244 matches = rl_completion_matches(text, complete_info);
2250 static int cmd_shell(int argc, char *argv[]) {
2252 xasprintf(&prompt, "%s> ", identname);
2256 int maxargs = argc + 16;
2257 char **nargv = xmalloc(maxargs * sizeof *nargv);
2259 for(int i = 0; i < argc; i++)
2262 #ifdef HAVE_READLINE
2263 rl_readline_name = "tinc";
2264 rl_completion_entry_function = complete_nothing;
2265 rl_attempted_completion_function = completion;
2266 rl_filename_completion_desired = 0;
2271 #ifdef HAVE_READLINE
2275 rl_basic_word_break_characters = "\t\n ";
2276 line = readline(prompt);
2278 copy = xstrdup(line);
2280 line = fgets(buf, sizeof buf, stdin);
2284 fputs(prompt, stdout);
2286 line = fgets(buf, sizeof buf, stdin);
2292 /* Ignore comments */
2300 char *p = line + strspn(line, " \t\n");
2301 char *next = strtok(p, " \t\n");
2304 if(nargc >= maxargs) {
2305 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2308 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2313 next = strtok(NULL, " \t\n");
2319 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2324 for(int i = 0; commands[i].command; i++) {
2325 if(!strcasecmp(nargv[argc], commands[i].command)) {
2326 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2332 #ifdef HAVE_READLINE
2338 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2351 int main(int argc, char *argv[]) {
2352 program_name = argv[0];
2356 if(!parse_options(argc, argv))
2360 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2361 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2376 tty = isatty(0) && isatty(1);
2379 return cmd_shell(argc, argv);
2381 for(int i = 0; commands[i].command; i++) {
2382 if(!strcasecmp(argv[optind], commands[i].command))
2383 return commands[i].function(argc - optind, argv + optind);
2386 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);