2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
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 #define MSG_NOSIGNAL 0
45 static char **orig_argv;
48 /* If nonzero, display usage information and exit. */
49 static bool show_help = false;
51 /* If nonzero, print the version on standard output and exit. */
52 static bool show_version = false;
54 static char *name = NULL;
55 static char controlcookie[1025];
56 char *tinc_conf = NULL;
57 char *hosts_dir = NULL;
60 // Horrible global variables...
67 static bool force = false;
69 bool confbasegiven = false;
70 bool netnamegiven = false;
71 char *scriptinterpreter = NULL;
72 char *scriptextension = "";
75 static struct option const long_options[] = {
76 {"config", required_argument, NULL, 'c'},
77 {"net", required_argument, NULL, 'n'},
78 {"help", no_argument, NULL, 1},
79 {"version", no_argument, NULL, 2},
80 {"pidfile", required_argument, NULL, 3},
81 {"force", no_argument, NULL, 4},
85 static void version(void) {
86 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
87 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
88 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
89 "See the AUTHORS file for a complete list.\n\n"
90 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
91 "and you are welcome to redistribute it under certain conditions;\n"
92 "see the file COPYING for details.\n");
95 static void usage(bool status) {
97 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
99 printf("Usage: %s [options] command\n\n", program_name);
100 printf("Valid options are:\n"
101 " -c, --config=DIR Read configuration options from DIR.\n"
102 " -n, --net=NETNAME Connect to net NETNAME.\n"
103 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
104 " --help Display this help and exit.\n"
105 " --version Output version information and exit.\n"
107 "Valid commands are:\n"
108 " init [name] Create initial configuration files.\n"
109 " get VARIABLE Print current value of VARIABLE\n"
110 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
111 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
112 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
113 " start [tincd options] Start tincd.\n"
114 " stop Stop tincd.\n"
115 " restart [tincd options] Restart tincd.\n"
116 " reload Partially reload configuration of running tincd.\n"
117 " pid Show PID of currently running tincd.\n"
118 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
119 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
120 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
121 " dump Dump a list of one of the following things:\n"
122 " [reachable] nodes - all known nodes in the VPN\n"
123 " edges - all known connections in the VPN\n"
124 " subnets - all known subnets in the VPN\n"
125 " connections - all meta connections with ourself\n"
126 " [di]graph - graph of the VPN in dotty format\n"
127 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
128 " purge Purge unreachable nodes\n"
129 " debug N Set debug level\n"
130 " retry Retry all outgoing connections\n"
131 " disconnect NODE Close meta connection with NODE\n"
133 " top Show real-time statistics\n"
135 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
136 " log [level] Dump log output [up to the specified level]\n"
137 " export Export host configuration of local node to standard output\n"
138 " export-all Export all host configuration files to standard output\n"
139 " import [--force] Import host configuration file(s) from standard input\n"
140 " exchange [--force] Same as export followed by import\n"
141 " exchange-all [--force] Same as export-all followed by import\n"
142 " invite NODE [...] Generate an invitation for NODE\n"
143 " join INVITATION Join a VPN using an INVITIATION\n"
144 " network [NETNAME] List all known networks, or switch to the one named NETNAME.\n"
146 printf("Report bugs to bugs@meshlink.io.\n");
150 static bool parse_options(int argc, char **argv) {
152 int option_index = 0;
154 while((r = getopt_long(argc, argv, "+c:n:", long_options, &option_index)) != EOF) {
156 case 0: /* long option */
159 case 'c': /* config file */
160 confbase = xstrdup(optarg);
161 confbasegiven = true;
164 case 'n': /* net name given */
165 netname = xstrdup(optarg);
168 case 1: /* show help */
172 case 2: /* show version */
176 case 3: /* open control socket here */
177 pidfilename = xstrdup(optarg);
184 case '?': /* wrong options */
193 if(!netname && (netname = getenv("NETNAME")))
194 netname = xstrdup(netname);
196 /* netname "." is special: a "top-level name" */
198 if(netname && (!*netname || !strcmp(netname, "."))) {
203 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
204 fprintf(stderr, "Invalid character in netname!\n");
211 /* Open a file with the desired permissions, minus the umask.
212 Also, if we want to create an executable file, we call fchmod()
213 to set the executable bits. */
215 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
216 mode_t mask = umask(0);
219 FILE *f = fopen(filename, mode);
221 if((perms & 0444) && f)
222 fchmod(fileno(f), perms);
228 static void disable_old_keys(const char *filename, const char *what) {
229 char tmpfile[PATH_MAX] = "";
231 bool disabled = false;
236 r = fopen(filename, "r");
240 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
242 struct stat st = {.st_mode = 0600};
243 fstat(fileno(r), &st);
244 w = fopenmask(tmpfile, "w", st.st_mode);
246 while(fgets(buf, sizeof buf, r)) {
247 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
248 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
254 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
260 if(block || ecdsapubkey)
262 if(fputs(buf, w) < 0) {
268 if(block && !strncmp(buf, "-----END ", 9))
275 if(ferror(r) || fclose(r) < 0)
280 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
287 // We cannot atomically replace files on Windows.
288 char bakfile[PATH_MAX] = "";
289 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
290 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
291 rename(bakfile, filename);
293 if(rename(tmpfile, filename)) {
295 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
300 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
307 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
313 /* Check stdin and stdout */
315 /* Ask for a file and/or directory name. */
316 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
318 if(fgets(buf, sizeof buf, stdin) == NULL) {
319 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
323 size_t len = strlen(buf);
332 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
334 if(filename[0] != '/') {
336 /* The directory is a relative path or a filename. */
337 directory = get_current_dir_name();
338 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
342 disable_old_keys(filename, what);
344 /* Open it first to keep the inode busy */
346 r = fopenmask(filename, mode, perms);
349 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
357 Generate a public/private ECDSA keypair, and ask for a file to store
360 static bool ecdsa_keygen(bool ask) {
363 char *pubname, *privname;
365 fprintf(stderr, "Generating ECDSA keypair:\n");
367 if(!(key = ecdsa_generate())) {
368 fprintf(stderr, "Error during key generation!\n");
371 fprintf(stderr, "Done.\n");
373 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
374 f = ask_and_open(privname, "private ECDSA key", "a", ask, 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, 0666);
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, 0600);
434 if(!rsa_write_pem_private_key(key, f)) {
435 fprintf(stderr, "Error writing private key!\n");
444 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
446 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
448 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
454 if(!rsa_write_pem_public_key(key, f)) {
455 fprintf(stderr, "Error writing public key!\n");
470 bool recvline(int fd, char *line, size_t len) {
471 char *newline = NULL;
476 while(!(newline = memchr(buffer, '\n', blen))) {
477 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
478 if(result == -1 && errno == EINTR)
485 if(newline - buffer >= len)
488 len = newline - buffer;
490 memcpy(line, buffer, len);
492 memmove(buffer, newline + 1, blen - len - 1);
498 bool recvdata(int fd, char *data, size_t len) {
503 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
504 if(result == -1 && errno == EINTR)
511 memcpy(data, buffer, len);
512 memmove(buffer, buffer + len, blen - len);
518 bool sendline(int fd, char *format, ...) {
519 static char buffer[4096];
524 va_start(ap, format);
525 blen = vsnprintf(buffer, sizeof buffer, format, ap);
528 if(blen < 1 || blen >= sizeof buffer)
535 int result = send(fd, p, blen, MSG_NOSIGNAL);
536 if(result == -1 && errno == EINTR)
547 static void pcap(int fd, FILE *out, int snaplen) {
548 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
556 uint32_t tz_accuracy;
563 snaplen ?: sizeof data,
576 fwrite(&header, sizeof header, 1, out);
580 while(recvline(fd, line, sizeof line)) {
582 int n = sscanf(line, "%d %d %d", &code, &req, &len);
583 gettimeofday(&tv, NULL);
584 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
586 if(!recvdata(fd, data, len))
588 packet.tv_sec = tv.tv_sec;
589 packet.tv_usec = tv.tv_usec;
591 packet.origlen = len;
592 fwrite(&packet, sizeof packet, 1, out);
593 fwrite(data, len, 1, out);
598 static void logcontrol(int fd, FILE *out, int level) {
599 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
603 while(recvline(fd, line, sizeof line)) {
605 int n = sscanf(line, "%d %d %d", &code, &req, &len);
606 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
608 if(!recvdata(fd, data, len))
610 fwrite(data, len, 1, out);
617 static bool remove_service(void) {
618 SC_HANDLE manager = NULL;
619 SC_HANDLE service = NULL;
620 SERVICE_STATUS status = {0};
622 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
624 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
628 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
631 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
635 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
636 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
638 fprintf(stderr, "%s service stopped\n", identname);
640 if(!DeleteService(service)) {
641 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
645 fprintf(stderr, "%s service removed\n", identname);
651 bool connect_tincd(bool verbose) {
656 struct timeval tv = {0, 0};
657 if(select(fd + 1, &r, NULL, NULL, &tv)) {
658 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
666 FILE *f = fopen(pidfilename, "r");
669 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
676 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
678 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
686 struct sockaddr_un sa;
687 sa.sun_family = AF_UNIX;
688 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
690 fd = socket(AF_UNIX, SOCK_STREAM, 0);
693 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
697 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
699 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
705 struct addrinfo hints = {
706 .ai_family = AF_UNSPEC,
707 .ai_socktype = SOCK_STREAM,
708 .ai_protocol = IPPROTO_TCP,
712 struct addrinfo *res = NULL;
714 if(getaddrinfo(host, port, &hints, &res) || !res) {
716 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
720 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
723 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
728 unsigned long arg = 0;
730 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
732 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
736 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
738 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
748 static const int one = 1;
749 setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, (void *)&one, sizeof one);
755 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
757 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
763 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
765 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
767 fprintf(stderr, "Could not fully establish control socket connection\n");
777 static int cmd_start(int argc, char *argv[]) {
778 if(connect_tincd(false)) {
780 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
782 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
787 char *slash = strrchr(program_name, '/');
790 if ((c = strrchr(program_name, '\\')) > slash)
795 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
800 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
803 for(int i = 1; i < optind; i++)
804 nargv[nargc++] = orig_argv[i];
805 for(int i = 1; i < argc; i++)
806 nargv[nargc++] = argv[i];
810 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
815 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
821 exit(execvp(c, nargv));
825 int status = -1, result;
827 signal(SIGINT, SIG_IGN);
829 result = waitpid(pid, &status, 0);
831 signal(SIGINT, SIG_DFL);
834 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
835 fprintf(stderr, "Error starting %s\n", c);
843 static int cmd_stop(int argc, char *argv[]) {
845 fprintf(stderr, "Too many arguments!\n");
850 if(!connect_tincd(true)) {
852 if(kill(pid, SIGTERM)) {
853 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
857 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
858 waitpid(pid, NULL, 0);
865 sendline(fd, "%d %d", CONTROL, REQ_STOP);
867 while(recvline(fd, line, sizeof line)) {
868 // Wait for tincd to close the connection...
871 if(!remove_service())
881 static int cmd_restart(int argc, char *argv[]) {
883 return cmd_start(argc, argv);
886 static int cmd_reload(int argc, char *argv[]) {
888 fprintf(stderr, "Too many arguments!\n");
892 if(!connect_tincd(true))
895 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
896 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
897 fprintf(stderr, "Could not reload configuration.\n");
905 static int cmd_dump(int argc, char *argv[]) {
906 bool only_reachable = false;
908 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
909 if(strcasecmp(argv[2], "nodes")) {
910 fprintf(stderr, "`reachable' only supported for nodes.\n");
914 only_reachable = true;
920 fprintf(stderr, "Invalid number of arguments.\n");
925 if(!connect_tincd(true))
930 if(!strcasecmp(argv[1], "nodes"))
931 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
932 else if(!strcasecmp(argv[1], "edges"))
933 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
934 else if(!strcasecmp(argv[1], "subnets"))
935 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
936 else if(!strcasecmp(argv[1], "connections"))
937 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
938 else if(!strcasecmp(argv[1], "graph")) {
939 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
940 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
942 } else if(!strcasecmp(argv[1], "digraph")) {
943 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
944 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
947 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
954 else if(do_graph == 2)
955 printf("digraph {\n");
957 while(recvline(fd, line, sizeof line)) {
958 char node1[4096], node2[4096];
959 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
961 if(do_graph && req == REQ_DUMP_NODES)
980 int cipher, digest, maclength, compression, distance, socket, weight;
981 short int pmtu, minmtu, maxmtu;
982 unsigned int options, status_int;
983 node_status_t status;
984 long int last_state_change;
987 case REQ_DUMP_NODES: {
988 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);
990 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
994 memcpy(&status, &status_int, sizeof status);
997 const char *color = "black";
998 if(!strcmp(host, "MYSELF"))
1000 else if(!status.reachable)
1002 else if(strcmp(via, node))
1004 else if(!status.validkey)
1008 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1010 if(only_reachable && !status.reachable)
1012 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",
1013 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1017 case REQ_DUMP_EDGES: {
1018 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1020 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1025 float w = 1 + 65536.0 / weight;
1026 if(do_graph == 1 && strcmp(node1, node2) > 0)
1027 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1028 else if(do_graph == 2)
1029 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1031 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1035 case REQ_DUMP_SUBNETS: {
1036 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1038 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1041 printf("%s owner %s\n", strip_weight(subnet), node);
1044 case REQ_DUMP_CONNECTIONS: {
1045 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1047 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1050 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1054 fprintf(stderr, "Unable to parse dump from tincd.\n");
1059 fprintf(stderr, "Error receiving dump.\n");
1063 static int cmd_purge(int argc, char *argv[]) {
1065 fprintf(stderr, "Too many arguments!\n");
1069 if(!connect_tincd(true))
1072 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1073 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1074 fprintf(stderr, "Could not purge old information.\n");
1081 static int cmd_debug(int argc, char *argv[]) {
1083 fprintf(stderr, "Invalid number of arguments.\n");
1087 if(!connect_tincd(true))
1090 int debuglevel = atoi(argv[1]);
1093 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1094 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1095 fprintf(stderr, "Could not set debug level.\n");
1099 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1103 static int cmd_retry(int argc, char *argv[]) {
1105 fprintf(stderr, "Too many arguments!\n");
1109 if(!connect_tincd(true))
1112 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1113 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1114 fprintf(stderr, "Could not retry outgoing connections.\n");
1121 static int cmd_connect(int argc, char *argv[]) {
1123 fprintf(stderr, "Invalid number of arguments.\n");
1127 if(!check_id(argv[1])) {
1128 fprintf(stderr, "Invalid name for node.\n");
1132 if(!connect_tincd(true))
1135 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1136 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1137 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1144 static int cmd_disconnect(int argc, char *argv[]) {
1146 fprintf(stderr, "Invalid number of arguments.\n");
1150 if(!check_id(argv[1])) {
1151 fprintf(stderr, "Invalid name for node.\n");
1155 if(!connect_tincd(true))
1158 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1159 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1160 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1167 static int cmd_top(int argc, char *argv[]) {
1169 fprintf(stderr, "Too many arguments!\n");
1174 if(!connect_tincd(true))
1180 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1185 static int cmd_pcap(int argc, char *argv[]) {
1187 fprintf(stderr, "Too many arguments!\n");
1191 if(!connect_tincd(true))
1194 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1199 static void sigint_handler(int sig) {
1200 fprintf(stderr, "\n");
1201 shutdown(fd, SHUT_RDWR);
1205 static int cmd_log(int argc, char *argv[]) {
1207 fprintf(stderr, "Too many arguments!\n");
1211 if(!connect_tincd(true))
1215 signal(SIGINT, sigint_handler);
1218 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1221 signal(SIGINT, SIG_DFL);
1229 static int cmd_pid(int argc, char *argv[]) {
1231 fprintf(stderr, "Too many arguments!\n");
1235 if(!connect_tincd(true) && !pid)
1238 printf("%d\n", pid);
1242 int rstrip(char *value) {
1243 int len = strlen(value);
1244 while(len && strchr("\t\r\n ", value[len - 1]))
1249 char *get_my_name(bool verbose) {
1250 FILE *f = fopen(tinc_conf, "r");
1253 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1259 while(fgets(buf, sizeof buf, f)) {
1260 int len = strcspn(buf, "\t =");
1262 value += strspn(value, "\t ");
1265 value += strspn(value, "\t ");
1270 if(strcasecmp(buf, "Name"))
1274 return strdup(value);
1280 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1284 const var_t variables[] = {
1285 /* Server configuration */
1286 {"AddressFamily", VAR_SERVER},
1287 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1288 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1289 {"BindToInterface", VAR_SERVER},
1290 {"Broadcast", VAR_SERVER | VAR_SAFE},
1291 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1292 {"DecrementTTL", VAR_SERVER},
1293 {"Device", VAR_SERVER},
1294 {"DeviceType", VAR_SERVER},
1295 {"DirectOnly", VAR_SERVER},
1296 {"ECDSAPrivateKeyFile", VAR_SERVER},
1297 {"ExperimentalProtocol", VAR_SERVER},
1298 {"Forwarding", VAR_SERVER},
1299 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1300 {"Hostnames", VAR_SERVER},
1301 {"IffOneQueue", VAR_SERVER},
1302 {"Interface", VAR_SERVER},
1303 {"KeyExpire", VAR_SERVER},
1304 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1305 {"LocalDiscovery", VAR_SERVER},
1306 {"MACExpire", VAR_SERVER},
1307 {"MaxConnectionBurst", VAR_SERVER},
1308 {"MaxOutputBufferSize", VAR_SERVER},
1309 {"MaxTimeout", VAR_SERVER},
1310 {"Mode", VAR_SERVER | VAR_SAFE},
1311 {"Name", VAR_SERVER},
1312 {"PingInterval", VAR_SERVER},
1313 {"PingTimeout", VAR_SERVER},
1314 {"PriorityInheritance", VAR_SERVER},
1315 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1316 {"PrivateKeyFile", VAR_SERVER},
1317 {"ProcessPriority", VAR_SERVER},
1318 {"Proxy", VAR_SERVER},
1319 {"ReplayWindow", VAR_SERVER},
1320 {"ScriptsExtension", VAR_SERVER},
1321 {"ScriptsInterpreter", VAR_SERVER},
1322 {"StrictSubnets", VAR_SERVER},
1323 {"TunnelServer", VAR_SERVER},
1324 {"VDEGroup", VAR_SERVER},
1325 {"VDEPort", VAR_SERVER},
1326 /* Host configuration */
1327 {"Address", VAR_HOST | VAR_MULTIPLE},
1328 {"Cipher", VAR_SERVER | VAR_HOST},
1329 {"ClampMSS", VAR_SERVER | VAR_HOST},
1330 {"Compression", VAR_SERVER | VAR_HOST},
1331 {"Digest", VAR_SERVER | VAR_HOST},
1332 {"ECDSAPublicKey", VAR_HOST},
1333 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1334 {"IndirectData", VAR_SERVER | VAR_HOST},
1335 {"MACLength", VAR_SERVER | VAR_HOST},
1336 {"PMTU", VAR_SERVER | VAR_HOST},
1337 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1339 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1340 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1341 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1342 {"TCPOnly", VAR_SERVER | VAR_HOST},
1343 {"Weight", VAR_HOST | VAR_SAFE},
1347 static int cmd_config(int argc, char *argv[]) {
1349 fprintf(stderr, "Invalid number of arguments.\n");
1353 if(strcasecmp(argv[0], "config"))
1357 if(!strcasecmp(argv[1], "get")) {
1359 } else if(!strcasecmp(argv[1], "add")) {
1360 argv++, argc--, action = 1;
1361 } else if(!strcasecmp(argv[1], "del")) {
1362 argv++, argc--, action = -1;
1363 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1364 argv++, argc--, action = 0;
1368 fprintf(stderr, "Invalid number of arguments.\n");
1372 // Concatenate the rest of the command line
1373 strncpy(line, argv[1], sizeof line - 1);
1374 for(int i = 2; i < argc; i++) {
1375 strncat(line, " ", sizeof line - 1 - strlen(line));
1376 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1379 // Liberal parsing into node name, variable name and value.
1385 len = strcspn(line, "\t =");
1387 value += strspn(value, "\t ");
1390 value += strspn(value, "\t ");
1393 variable = strchr(line, '.');
1402 fprintf(stderr, "No variable given.\n");
1406 if(action >= 0 && !*value) {
1407 fprintf(stderr, "No value for variable given.\n");
1411 if(action < -1 && *value)
1414 /* Some simple checks. */
1416 bool warnonremove = false;
1418 for(int i = 0; variables[i].name; i++) {
1419 if(strcasecmp(variables[i].name, variable))
1423 variable = (char *)variables[i].name;
1425 /* Discourage use of obsolete variables. */
1427 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1429 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1431 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1436 /* Don't put server variables in host config files */
1438 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1440 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1442 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1447 /* Should this go into our own host config file? */
1449 if(!node && !(variables[i].type & VAR_SERVER)) {
1450 node = get_my_name(true);
1455 /* Change "add" into "set" for variables that do not allow multiple occurences.
1456 Turn on warnings when it seems variables might be removed unintentionally. */
1458 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1459 warnonremove = true;
1461 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1462 warnonremove = true;
1468 if(node && !check_id(node)) {
1469 fprintf(stderr, "Invalid name for node.\n");
1474 if(force || action < 0) {
1475 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1477 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1482 // Open the right configuration file.
1485 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1487 filename = tinc_conf;
1489 FILE *f = fopen(filename, "r");
1491 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1495 char *tmpfile = NULL;
1499 xasprintf(&tmpfile, "%s.config.tmp", filename);
1500 tf = fopen(tmpfile, "w");
1502 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1508 // Copy the file, making modifications on the fly, unless we are just getting a value.
1512 bool removed = false;
1515 while(fgets(buf1, sizeof buf1, f)) {
1516 buf1[sizeof buf1 - 1] = 0;
1517 strncpy(buf2, buf1, sizeof buf2);
1519 // Parse line in a simple way
1523 len = strcspn(buf2, "\t =");
1524 bvalue = buf2 + len;
1525 bvalue += strspn(bvalue, "\t ");
1526 if(*bvalue == '=') {
1528 bvalue += strspn(bvalue, "\t ");
1534 if(!strcasecmp(buf2, variable)) {
1538 printf("%s\n", bvalue);
1540 } else if(action == -1) {
1541 if(!*value || !strcasecmp(bvalue, value)) {
1546 } else if(action == 0) {
1547 // Warn if "set" was used for variables that can occur multiple times
1548 if(warnonremove && strcasecmp(bvalue, value))
1549 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1551 // Already set? Delete the rest...
1555 // Otherwise, replace.
1556 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1557 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1566 // Copy original line...
1567 if(fputs(buf1, tf) < 0) {
1568 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1572 // Add newline if it is missing...
1573 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1574 if(fputc('\n', tf) < 0) {
1575 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1582 // Make sure we read everything...
1583 if(ferror(f) || !feof(f)) {
1584 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1589 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1593 // Add new variable if necessary.
1594 if(action > 0 || (action == 0 && !set)) {
1595 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1596 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1603 fprintf(stderr, "No matching configuration variables found.\n");
1607 // Make sure we wrote everything...
1609 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1613 // Could we find what we had to remove?
1614 if(action < 0 && !removed) {
1616 fprintf(stderr, "No configuration variables deleted.\n");
1620 // Replace the configuration file with the new one
1622 if(remove(filename)) {
1623 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1627 if(rename(tmpfile, filename)) {
1628 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1632 // Silently try notifying a running tincd of changes.
1633 if(connect_tincd(false))
1634 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1639 bool check_id(const char *name) {
1643 for(int i = 0; i < strlen(name); i++) {
1644 if(!isalnum(name[i]) && name[i] != '_')
1651 static bool try_bind(int port) {
1652 struct addrinfo *ai = NULL;
1653 struct addrinfo hint = {
1654 .ai_flags = AI_PASSIVE,
1655 .ai_family = AF_UNSPEC,
1656 .ai_socktype = SOCK_STREAM,
1657 .ai_protocol = IPPROTO_TCP,
1661 snprintf(portstr, sizeof portstr, "%d", port);
1663 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1667 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1670 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1680 int check_port(char *name) {
1684 fprintf(stderr, "Warning: could not bind to port 655. ");
1686 for(int i = 0; i < 100; i++) {
1687 int port = 0x1000 + (rand() & 0x7fff);
1688 if(try_bind(port)) {
1690 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1691 FILE *f = fopen(filename, "a");
1694 fprintf(stderr, "Please change tinc's Port manually.\n");
1698 fprintf(f, "Port = %d\n", port);
1700 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1705 fprintf(stderr, "Please change tinc's Port manually.\n");
1709 static int cmd_init(int argc, char *argv[]) {
1710 if(!access(tinc_conf, F_OK)) {
1711 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1716 fprintf(stderr, "Too many arguments!\n");
1718 } else if(argc < 2) {
1721 fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1722 if(!fgets(buf, sizeof buf, stdin)) {
1723 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1726 int len = rstrip(buf);
1728 fprintf(stderr, "No name given!\n");
1733 fprintf(stderr, "No Name given!\n");
1737 name = strdup(argv[1]);
1739 fprintf(stderr, "No Name given!\n");
1744 if(!check_id(name)) {
1745 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1749 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1750 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1754 if(mkdir(confbase, 0777) && errno != EEXIST) {
1755 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1759 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1760 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1764 FILE *f = fopen(tinc_conf, "w");
1766 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1770 fprintf(f, "Name = %s\n", name);
1773 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1780 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1781 if(access(filename, F_OK)) {
1782 FILE *f = fopenmask(filename, "w", 0777);
1784 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1787 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit '$0'!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1796 static int cmd_generate_keys(int argc, char *argv[]) {
1798 fprintf(stderr, "Too many arguments!\n");
1803 name = get_my_name(false);
1805 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1808 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1810 fprintf(stderr, "Too many arguments!\n");
1815 name = get_my_name(false);
1817 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1820 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1822 fprintf(stderr, "Too many arguments!\n");
1827 name = get_my_name(false);
1829 return !ecdsa_keygen(true);
1832 static int cmd_help(int argc, char *argv[]) {
1837 static int cmd_version(int argc, char *argv[]) {
1839 fprintf(stderr, "Too many arguments!\n");
1847 static int cmd_info(int argc, char *argv[]) {
1849 fprintf(stderr, "Invalid number of arguments.\n");
1853 if(!connect_tincd(true))
1856 return info(fd, argv[1]);
1859 static const char *conffiles[] = {
1870 static int cmd_edit(int argc, char *argv[]) {
1872 fprintf(stderr, "Invalid number of arguments.\n");
1876 char *filename = NULL;
1878 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1879 for(int i = 0; conffiles[i]; i++) {
1880 if(!strcmp(argv[1], conffiles[i])) {
1881 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1890 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1891 char *dash = strchr(argv[1], '-');
1894 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1895 fprintf(stderr, "Invalid configuration filename.\n");
1903 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1905 xasprintf(&command, "edit \"%s\"", filename);
1907 int result = system(command);
1911 // Silently try notifying a running tincd of changes.
1912 if(connect_tincd(false))
1913 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1918 static int export(const char *name, FILE *out) {
1920 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1921 FILE *in = fopen(filename, "r");
1923 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1927 fprintf(out, "Name = %s\n", name);
1929 while(fgets(buf, sizeof buf, in)) {
1930 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1935 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1944 static int cmd_export(int argc, char *argv[]) {
1946 fprintf(stderr, "Too many arguments!\n");
1950 char *name = get_my_name(true);
1954 int result = export(name, stdout);
1962 static int cmd_export_all(int argc, char *argv[]) {
1964 fprintf(stderr, "Too many arguments!\n");
1968 DIR *dir = opendir(hosts_dir);
1970 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1978 while((ent = readdir(dir))) {
1979 if(!check_id(ent->d_name))
1985 printf("#---------------------------------------------------------------#\n");
1987 result |= export(ent->d_name, stdout);
1996 static int cmd_import(int argc, char *argv[]) {
1998 fprintf(stderr, "Too many arguments!\n");
2007 char *filename = NULL;
2009 bool firstline = true;
2011 while(fgets(buf, sizeof buf, in)) {
2012 if(sscanf(buf, "Name = %s", name) == 1) {
2015 if(!check_id(name)) {
2016 fprintf(stderr, "Invalid Name in input!\n");
2024 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2026 if(!force && !access(filename, F_OK)) {
2027 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2032 out = fopen(filename, "w");
2034 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2040 } else if(firstline) {
2041 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2046 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2050 if(fputs(buf, out) < 0) {
2051 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2061 fprintf(stderr, "Imported %d host configuration files.\n", count);
2064 fprintf(stderr, "No host configuration files imported.\n");
2069 static int cmd_exchange(int argc, char *argv[]) {
2070 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2073 static int cmd_exchange_all(int argc, char *argv[]) {
2074 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2077 static int switch_network(char *name) {
2089 free(unixsocketname);
2090 unixsocketname = NULL;
2096 netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2098 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2099 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2100 xasprintf(&prompt, "%s> ", identname);
2105 static int cmd_network(int argc, char *argv[]) {
2107 fprintf(stderr, "Too many arguments!\n");
2112 return switch_network(argv[1]);
2114 DIR *dir = opendir(confdir);
2116 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2121 while((ent = readdir(dir))) {
2122 if(*ent->d_name == '.')
2125 if(!strcmp(ent->d_name, "tinc.conf")) {
2131 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2132 if(!access(fname, R_OK))
2133 printf("%s\n", ent->d_name);
2140 static const struct {
2141 const char *command;
2142 int (*function)(int argc, char *argv[]);
2145 {"start", cmd_start},
2147 {"restart", cmd_restart},
2148 {"reload", cmd_reload},
2150 {"purge", cmd_purge},
2151 {"debug", cmd_debug},
2152 {"retry", cmd_retry},
2153 {"connect", cmd_connect},
2154 {"disconnect", cmd_disconnect},
2159 {"config", cmd_config, true},
2160 {"add", cmd_config},
2161 {"del", cmd_config},
2162 {"get", cmd_config},
2163 {"set", cmd_config},
2165 {"generate-keys", cmd_generate_keys},
2166 {"generate-rsa-keys", cmd_generate_rsa_keys},
2167 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2169 {"version", cmd_version},
2172 {"export", cmd_export},
2173 {"export-all", cmd_export_all},
2174 {"import", cmd_import},
2175 {"exchange", cmd_exchange},
2176 {"exchange-all", cmd_exchange_all},
2177 {"invite", cmd_invite},
2179 {"network", cmd_network},
2183 #ifdef HAVE_READLINE
2184 static char *complete_command(const char *text, int state) {
2192 while(commands[i].command) {
2193 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2194 return xstrdup(commands[i].command);
2201 static char *complete_dump(const char *text, int state) {
2202 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2211 if(!strncasecmp(matches[i], text, strlen(text)))
2212 return xstrdup(matches[i]);
2219 static char *complete_config(const char *text, int state) {
2227 while(variables[i].name) {
2228 char *dot = strchr(text, '.');
2230 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2232 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2236 if(!strncasecmp(variables[i].name, text, strlen(text)))
2237 return xstrdup(variables[i].name);
2245 static char *complete_info(const char *text, int state) {
2249 if(!connect_tincd(false))
2251 // Check the list of nodes
2252 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2253 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2256 while(recvline(fd, line, sizeof line)) {
2258 int n = sscanf(line, "%d %d %s", &code, &req, item);
2268 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2272 if(!strncmp(item, text, strlen(text)))
2273 return xstrdup(strip_weight(item));
2279 static char *complete_nothing(const char *text, int state) {
2283 static char **completion (const char *text, int start, int end) {
2284 char **matches = NULL;
2287 matches = rl_completion_matches(text, complete_command);
2288 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2289 matches = rl_completion_matches(text, complete_dump);
2290 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2291 matches = rl_completion_matches(text, complete_config);
2292 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2293 matches = rl_completion_matches(text, complete_config);
2294 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2295 matches = rl_completion_matches(text, complete_config);
2296 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2297 matches = rl_completion_matches(text, complete_config);
2298 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2299 matches = rl_completion_matches(text, complete_info);
2305 static int cmd_shell(int argc, char *argv[]) {
2306 xasprintf(&prompt, "%s> ", identname);
2310 int maxargs = argc + 16;
2311 char **nargv = xmalloc(maxargs * sizeof *nargv);
2313 for(int i = 0; i < argc; i++)
2316 #ifdef HAVE_READLINE
2317 rl_readline_name = "tinc";
2318 rl_completion_entry_function = complete_nothing;
2319 rl_attempted_completion_function = completion;
2320 rl_filename_completion_desired = 0;
2325 #ifdef HAVE_READLINE
2329 rl_basic_word_break_characters = "\t\n ";
2330 line = readline(prompt);
2332 copy = xstrdup(line);
2334 line = fgets(buf, sizeof buf, stdin);
2338 fputs(prompt, stdout);
2340 line = fgets(buf, sizeof buf, stdin);
2346 /* Ignore comments */
2354 char *p = line + strspn(line, " \t\n");
2355 char *next = strtok(p, " \t\n");
2358 if(nargc >= maxargs) {
2359 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2362 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2367 next = strtok(NULL, " \t\n");
2373 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2378 for(int i = 0; commands[i].command; i++) {
2379 if(!strcasecmp(nargv[argc], commands[i].command)) {
2380 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2386 #ifdef HAVE_READLINE
2392 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2405 int main(int argc, char *argv[]) {
2406 program_name = argv[0];
2410 if(!parse_options(argc, argv))
2413 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2414 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2427 static struct WSAData wsa_state;
2429 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2430 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2438 tty = isatty(0) && isatty(1);
2441 return cmd_shell(argc, argv);
2443 for(int i = 0; commands[i].command; i++) {
2444 if(!strcasecmp(argv[optind], commands[i].command))
2445 return commands[i].function(argc - optind, argv + optind);
2448 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);