2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2014 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 MSG_NOSIGNAL 0
46 static char **orig_argv;
49 /* If nonzero, display usage information and exit. */
50 static bool show_help = false;
52 /* If nonzero, print the version on standard output and exit. */
53 static bool show_version = false;
55 static char *name = NULL;
56 static char controlcookie[1025];
57 char *tinc_conf = NULL;
58 char *hosts_dir = NULL;
61 // Horrible global variables...
68 static bool force = false;
70 bool confbasegiven = false;
71 bool netnamegiven = false;
72 char *scriptinterpreter = NULL;
73 char *scriptextension = "";
76 static struct option const long_options[] = {
77 {"config", required_argument, NULL, 'c'},
78 {"net", required_argument, NULL, 'n'},
79 {"help", no_argument, NULL, 1},
80 {"version", no_argument, NULL, 2},
81 {"pidfile", required_argument, NULL, 3},
82 {"force", no_argument, NULL, 4},
86 static void version(void) {
87 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
88 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
89 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
90 "See the AUTHORS file for a complete list.\n\n"
91 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
92 "and you are welcome to redistribute it under certain conditions;\n"
93 "see the file COPYING for details.\n");
96 static void usage(bool status) {
98 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
100 printf("Usage: %s [options] command\n\n", program_name);
101 printf("Valid options are:\n"
102 " -c, --config=DIR Read configuration options from DIR.\n"
103 " -n, --net=NETNAME Connect to net NETNAME.\n"
104 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
105 " --help Display this help and exit.\n"
106 " --version Output version information and exit.\n"
108 "Valid commands are:\n"
109 " init [name] Create initial configuration files.\n"
110 " get VARIABLE Print current value of VARIABLE\n"
111 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
112 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
113 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
114 " start [tincd options] Start tincd.\n"
115 " stop Stop tincd.\n"
116 " restart [tincd options] Restart tincd.\n"
117 " reload Partially reload configuration of running tincd.\n"
118 " pid Show PID of currently running tincd.\n"
119 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
120 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
121 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
122 " dump Dump a list of one of the following things:\n"
123 " [reachable] nodes - all known nodes in the VPN\n"
124 " edges - all known connections in the VPN\n"
125 " subnets - all known subnets in the VPN\n"
126 " connections - all meta connections with ourself\n"
127 " [di]graph - graph of the VPN in dotty format\n"
128 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
129 " purge Purge unreachable nodes\n"
130 " debug N Set debug level\n"
131 " retry Retry all outgoing connections\n"
132 " disconnect NODE Close meta connection with NODE\n"
134 " top Show real-time statistics\n"
136 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
137 " log [level] Dump log output [up to the specified level]\n"
138 " export Export host configuration of local node to standard output\n"
139 " export-all Export all host configuration files to standard output\n"
140 " import [--force] Import host configuration file(s) from standard input\n"
141 " exchange [--force] Same as export followed by import\n"
142 " exchange-all [--force] Same as export-all followed by import\n"
143 " invite NODE [...] Generate an invitation for NODE\n"
144 " join INVITATION Join a VPN using an INVITIATION\n"
145 " network [NETNAME] List all known networks, or switch to the one named NETNAME.\n"
147 printf("Report bugs to tinc@tinc-vpn.org.\n");
151 static bool parse_options(int argc, char **argv) {
153 int option_index = 0;
155 while((r = getopt_long(argc, argv, "+c:n:", long_options, &option_index)) != EOF) {
157 case 0: /* long option */
160 case 'c': /* config file */
161 confbase = xstrdup(optarg);
162 confbasegiven = true;
165 case 'n': /* net name given */
166 netname = xstrdup(optarg);
169 case 1: /* show help */
173 case 2: /* show version */
177 case 3: /* open control socket here */
178 pidfilename = xstrdup(optarg);
185 case '?': /* wrong options */
194 if(!netname && (netname = getenv("NETNAME")))
195 netname = xstrdup(netname);
197 /* netname "." is special: a "top-level name" */
199 if(netname && (!*netname || !strcmp(netname, "."))) {
204 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
205 fprintf(stderr, "Invalid character in netname!\n");
212 /* Open a file with the desired permissions, minus the umask.
213 Also, if we want to create an executable file, we call fchmod()
214 to set the executable bits. */
216 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
217 mode_t mask = umask(0);
220 FILE *f = fopen(filename, mode);
222 if((perms & 0444) && f)
223 fchmod(fileno(f), perms);
229 static void disable_old_keys(const char *filename, const char *what) {
230 char tmpfile[PATH_MAX] = "";
232 bool disabled = false;
237 r = fopen(filename, "r");
241 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
243 struct stat st = {.st_mode = 0600};
244 fstat(fileno(r), &st);
245 w = fopenmask(tmpfile, "w", st.st_mode);
247 while(fgets(buf, sizeof buf, r)) {
248 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
249 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
255 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
261 if(block || ecdsapubkey)
263 if(fputs(buf, w) < 0) {
269 if(block && !strncmp(buf, "-----END ", 9))
276 if(ferror(r) || fclose(r) < 0)
281 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
288 // We cannot atomically replace files on Windows.
289 char bakfile[PATH_MAX] = "";
290 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
291 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
292 rename(bakfile, filename);
294 if(rename(tmpfile, filename)) {
296 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
301 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
308 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
314 /* Check stdin and stdout */
316 /* Ask for a file and/or directory name. */
317 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
319 if(fgets(buf, sizeof buf, stdin) == NULL) {
320 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
324 size_t len = strlen(buf);
333 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
335 if(filename[0] != '/') {
337 /* The directory is a relative path or a filename. */
338 directory = get_current_dir_name();
339 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
343 disable_old_keys(filename, what);
345 /* Open it first to keep the inode busy */
347 r = fopenmask(filename, mode, perms);
350 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
358 Generate a public/private ECDSA keypair, and ask for a file to store
361 static bool ecdsa_keygen(bool ask) {
364 char *pubname, *privname;
366 fprintf(stderr, "Generating ECDSA keypair:\n");
368 if(!(key = ecdsa_generate())) {
369 fprintf(stderr, "Error during key generation!\n");
372 fprintf(stderr, "Done.\n");
374 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
375 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
381 if(!ecdsa_write_pem_private_key(key, f)) {
382 fprintf(stderr, "Error writing private key!\n");
391 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
393 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
395 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
401 char *pubkey = ecdsa_get_base64_public_key(key);
402 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
412 Generate a public/private RSA keypair, and ask for a file to store
415 static bool rsa_keygen(int bits, bool ask) {
418 char *pubname, *privname;
420 fprintf(stderr, "Generating %d bits keys:\n", bits);
422 if(!(key = rsa_generate(bits, 0x10001))) {
423 fprintf(stderr, "Error during key generation!\n");
426 fprintf(stderr, "Done.\n");
428 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
429 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
435 if(!rsa_write_pem_private_key(key, f)) {
436 fprintf(stderr, "Error writing private key!\n");
445 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
447 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
449 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
455 if(!rsa_write_pem_public_key(key, f)) {
456 fprintf(stderr, "Error writing public key!\n");
471 bool recvline(int fd, char *line, size_t len) {
472 char *newline = NULL;
477 while(!(newline = memchr(buffer, '\n', blen))) {
478 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
479 if(result == -1 && errno == EINTR)
486 if(newline - buffer >= len)
489 len = newline - buffer;
491 memcpy(line, buffer, len);
493 memmove(buffer, newline + 1, blen - len - 1);
499 bool recvdata(int fd, char *data, size_t len) {
504 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
505 if(result == -1 && errno == EINTR)
512 memcpy(data, buffer, len);
513 memmove(buffer, buffer + len, blen - len);
519 bool sendline(int fd, char *format, ...) {
520 static char buffer[4096];
525 va_start(ap, format);
526 blen = vsnprintf(buffer, sizeof buffer, format, ap);
529 if(blen < 1 || blen >= sizeof buffer)
536 int result = send(fd, p, blen, MSG_NOSIGNAL);
537 if(result == -1 && errno == EINTR)
548 static void pcap(int fd, FILE *out, int snaplen) {
549 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
557 uint32_t tz_accuracy;
564 snaplen ?: sizeof data,
577 fwrite(&header, sizeof header, 1, out);
581 while(recvline(fd, line, sizeof line)) {
583 int n = sscanf(line, "%d %d %d", &code, &req, &len);
584 gettimeofday(&tv, NULL);
585 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
587 if(!recvdata(fd, data, len))
589 packet.tv_sec = tv.tv_sec;
590 packet.tv_usec = tv.tv_usec;
592 packet.origlen = len;
593 fwrite(&packet, sizeof packet, 1, out);
594 fwrite(data, len, 1, out);
599 static void logcontrol(int fd, FILE *out, int level) {
600 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
604 while(recvline(fd, line, sizeof line)) {
606 int n = sscanf(line, "%d %d %d", &code, &req, &len);
607 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
609 if(!recvdata(fd, data, len))
611 fwrite(data, len, 1, out);
618 static bool remove_service(void) {
619 SC_HANDLE manager = NULL;
620 SC_HANDLE service = NULL;
621 SERVICE_STATUS status = {0};
623 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
625 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
629 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
632 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
636 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
637 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
639 fprintf(stderr, "%s service stopped\n", identname);
641 if(!DeleteService(service)) {
642 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
646 fprintf(stderr, "%s service removed\n", identname);
652 bool connect_tincd(bool verbose) {
657 struct timeval tv = {0, 0};
658 if(select(fd + 1, &r, NULL, NULL, &tv)) {
659 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
667 FILE *f = fopen(pidfilename, "r");
670 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
677 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
679 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
687 struct sockaddr_un sa;
688 sa.sun_family = AF_UNIX;
689 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
691 fd = socket(AF_UNIX, SOCK_STREAM, 0);
694 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
698 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
700 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
706 struct addrinfo hints = {
707 .ai_family = AF_UNSPEC,
708 .ai_socktype = SOCK_STREAM,
709 .ai_protocol = IPPROTO_TCP,
713 struct addrinfo *res = NULL;
715 if(getaddrinfo(host, port, &hints, &res) || !res) {
717 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
721 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
724 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
729 unsigned long arg = 0;
731 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
733 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
737 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
739 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
749 static const int one = 1;
750 setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, (void *)&one, sizeof one);
756 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
758 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
764 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
766 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
768 fprintf(stderr, "Could not fully establish control socket connection\n");
778 static int cmd_start(int argc, char *argv[]) {
779 if(connect_tincd(false)) {
781 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
783 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
788 char *slash = strrchr(program_name, '/');
791 if ((c = strrchr(program_name, '\\')) > slash)
796 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
801 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
804 for(int i = 1; i < optind; i++)
805 nargv[nargc++] = orig_argv[i];
806 for(int i = 1; i < argc; i++)
807 nargv[nargc++] = argv[i];
811 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
816 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
822 exit(execvp(c, nargv));
826 int status = -1, result;
828 signal(SIGINT, SIG_IGN);
830 result = waitpid(pid, &status, 0);
832 signal(SIGINT, SIG_DFL);
835 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
836 fprintf(stderr, "Error starting %s\n", c);
844 static int cmd_stop(int argc, char *argv[]) {
846 fprintf(stderr, "Too many arguments!\n");
851 if(!connect_tincd(true)) {
853 if(kill(pid, SIGTERM)) {
854 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
858 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
859 waitpid(pid, NULL, 0);
866 sendline(fd, "%d %d", CONTROL, REQ_STOP);
868 while(recvline(fd, line, sizeof line)) {
869 // Wait for tincd to close the connection...
872 if(!remove_service())
882 static int cmd_restart(int argc, char *argv[]) {
884 return cmd_start(argc, argv);
887 static int cmd_reload(int argc, char *argv[]) {
889 fprintf(stderr, "Too many arguments!\n");
893 if(!connect_tincd(true))
896 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
897 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
898 fprintf(stderr, "Could not reload configuration.\n");
906 static int cmd_dump(int argc, char *argv[]) {
907 bool only_reachable = false;
909 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
910 if(strcasecmp(argv[2], "nodes")) {
911 fprintf(stderr, "`reachable' only supported for nodes.\n");
915 only_reachable = true;
921 fprintf(stderr, "Invalid number of arguments.\n");
926 if(!connect_tincd(true))
931 if(!strcasecmp(argv[1], "nodes"))
932 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
933 else if(!strcasecmp(argv[1], "edges"))
934 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
935 else if(!strcasecmp(argv[1], "subnets"))
936 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
937 else if(!strcasecmp(argv[1], "connections"))
938 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
939 else if(!strcasecmp(argv[1], "graph")) {
940 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
941 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
943 } else if(!strcasecmp(argv[1], "digraph")) {
944 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
945 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
948 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
955 else if(do_graph == 2)
956 printf("digraph {\n");
958 while(recvline(fd, line, sizeof line)) {
959 char node1[4096], node2[4096];
960 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
962 if(do_graph && req == REQ_DUMP_NODES)
981 int cipher, digest, maclength, compression, distance, socket, weight;
982 short int pmtu, minmtu, maxmtu;
983 unsigned int options, status_int;
984 node_status_t status;
985 long int last_state_change;
988 case REQ_DUMP_NODES: {
989 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);
991 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
995 memcpy(&status, &status_int, sizeof status);
998 const char *color = "black";
999 if(!strcmp(host, "MYSELF"))
1001 else if(!status.reachable)
1003 else if(strcmp(via, node))
1005 else if(!status.validkey)
1009 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1011 if(only_reachable && !status.reachable)
1013 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",
1014 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1018 case REQ_DUMP_EDGES: {
1019 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1021 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1026 float w = 1 + 65536.0 / weight;
1027 if(do_graph == 1 && strcmp(node1, node2) > 0)
1028 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1029 else if(do_graph == 2)
1030 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1032 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1036 case REQ_DUMP_SUBNETS: {
1037 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1039 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1042 printf("%s owner %s\n", strip_weight(subnet), node);
1045 case REQ_DUMP_CONNECTIONS: {
1046 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1048 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1051 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1055 fprintf(stderr, "Unable to parse dump from tincd.\n");
1060 fprintf(stderr, "Error receiving dump.\n");
1064 static int cmd_purge(int argc, char *argv[]) {
1066 fprintf(stderr, "Too many arguments!\n");
1070 if(!connect_tincd(true))
1073 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1074 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1075 fprintf(stderr, "Could not purge old information.\n");
1082 static int cmd_debug(int argc, char *argv[]) {
1084 fprintf(stderr, "Invalid number of arguments.\n");
1088 if(!connect_tincd(true))
1091 int debuglevel = atoi(argv[1]);
1094 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1095 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1096 fprintf(stderr, "Could not set debug level.\n");
1100 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1104 static int cmd_retry(int argc, char *argv[]) {
1106 fprintf(stderr, "Too many arguments!\n");
1110 if(!connect_tincd(true))
1113 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1114 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1115 fprintf(stderr, "Could not retry outgoing connections.\n");
1122 static int cmd_connect(int argc, char *argv[]) {
1124 fprintf(stderr, "Invalid number of arguments.\n");
1128 if(!check_id(argv[1])) {
1129 fprintf(stderr, "Invalid name for node.\n");
1133 if(!connect_tincd(true))
1136 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1137 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1138 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1145 static int cmd_disconnect(int argc, char *argv[]) {
1147 fprintf(stderr, "Invalid number of arguments.\n");
1151 if(!check_id(argv[1])) {
1152 fprintf(stderr, "Invalid name for node.\n");
1156 if(!connect_tincd(true))
1159 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1160 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1161 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1168 static int cmd_top(int argc, char *argv[]) {
1170 fprintf(stderr, "Too many arguments!\n");
1175 if(!connect_tincd(true))
1181 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1186 static int cmd_pcap(int argc, char *argv[]) {
1188 fprintf(stderr, "Too many arguments!\n");
1192 if(!connect_tincd(true))
1195 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1200 static void sigint_handler(int sig) {
1201 fprintf(stderr, "\n");
1202 shutdown(fd, SHUT_RDWR);
1206 static int cmd_log(int argc, char *argv[]) {
1208 fprintf(stderr, "Too many arguments!\n");
1212 if(!connect_tincd(true))
1216 signal(SIGINT, sigint_handler);
1219 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1222 signal(SIGINT, SIG_DFL);
1230 static int cmd_pid(int argc, char *argv[]) {
1232 fprintf(stderr, "Too many arguments!\n");
1236 if(!connect_tincd(true) && !pid)
1239 printf("%d\n", pid);
1243 int rstrip(char *value) {
1244 int len = strlen(value);
1245 while(len && strchr("\t\r\n ", value[len - 1]))
1250 char *get_my_name(bool verbose) {
1251 FILE *f = fopen(tinc_conf, "r");
1254 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1260 while(fgets(buf, sizeof buf, f)) {
1261 int len = strcspn(buf, "\t =");
1263 value += strspn(value, "\t ");
1266 value += strspn(value, "\t ");
1271 if(strcasecmp(buf, "Name"))
1275 return strdup(value);
1281 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1285 const var_t variables[] = {
1286 /* Server configuration */
1287 {"AddressFamily", VAR_SERVER},
1288 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1289 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1290 {"BindToInterface", VAR_SERVER},
1291 {"Broadcast", VAR_SERVER | VAR_SAFE},
1292 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1293 {"DecrementTTL", VAR_SERVER},
1294 {"Device", VAR_SERVER},
1295 {"DeviceType", VAR_SERVER},
1296 {"DirectOnly", VAR_SERVER},
1297 {"ECDSAPrivateKeyFile", VAR_SERVER},
1298 {"ExperimentalProtocol", VAR_SERVER},
1299 {"Forwarding", VAR_SERVER},
1300 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1301 {"Hostnames", VAR_SERVER},
1302 {"IffOneQueue", VAR_SERVER},
1303 {"Interface", VAR_SERVER},
1304 {"KeyExpire", VAR_SERVER},
1305 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1306 {"LocalDiscovery", VAR_SERVER},
1307 {"MACExpire", VAR_SERVER},
1308 {"MaxConnectionBurst", VAR_SERVER},
1309 {"MaxOutputBufferSize", VAR_SERVER},
1310 {"MaxTimeout", VAR_SERVER},
1311 {"Mode", VAR_SERVER | VAR_SAFE},
1312 {"Name", VAR_SERVER},
1313 {"PingInterval", VAR_SERVER},
1314 {"PingTimeout", VAR_SERVER},
1315 {"PriorityInheritance", VAR_SERVER},
1316 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1317 {"PrivateKeyFile", VAR_SERVER},
1318 {"ProcessPriority", VAR_SERVER},
1319 {"Proxy", VAR_SERVER},
1320 {"ReplayWindow", VAR_SERVER},
1321 {"ScriptsExtension", VAR_SERVER},
1322 {"ScriptsInterpreter", VAR_SERVER},
1323 {"StrictSubnets", VAR_SERVER},
1324 {"TunnelServer", VAR_SERVER},
1325 {"UDPRcvBuf", VAR_SERVER},
1326 {"UDPSndBuf", VAR_SERVER},
1327 {"VDEGroup", VAR_SERVER},
1328 {"VDEPort", VAR_SERVER},
1329 /* Host configuration */
1330 {"Address", VAR_HOST | VAR_MULTIPLE},
1331 {"Cipher", VAR_SERVER | VAR_HOST},
1332 {"ClampMSS", VAR_SERVER | VAR_HOST},
1333 {"Compression", VAR_SERVER | VAR_HOST},
1334 {"Digest", VAR_SERVER | VAR_HOST},
1335 {"ECDSAPublicKey", VAR_HOST},
1336 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1337 {"IndirectData", VAR_SERVER | VAR_HOST},
1338 {"MACLength", VAR_SERVER | VAR_HOST},
1339 {"PMTU", VAR_SERVER | VAR_HOST},
1340 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1342 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1343 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1344 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1345 {"TCPOnly", VAR_SERVER | VAR_HOST},
1346 {"Weight", VAR_HOST | VAR_SAFE},
1350 static int cmd_config(int argc, char *argv[]) {
1352 fprintf(stderr, "Invalid number of arguments.\n");
1356 if(strcasecmp(argv[0], "config"))
1360 if(!strcasecmp(argv[1], "get")) {
1362 } else if(!strcasecmp(argv[1], "add")) {
1363 argv++, argc--, action = 1;
1364 } else if(!strcasecmp(argv[1], "del")) {
1365 argv++, argc--, action = -1;
1366 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1367 argv++, argc--, action = 0;
1371 fprintf(stderr, "Invalid number of arguments.\n");
1375 // Concatenate the rest of the command line
1376 strncpy(line, argv[1], sizeof line - 1);
1377 for(int i = 2; i < argc; i++) {
1378 strncat(line, " ", sizeof line - 1 - strlen(line));
1379 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1382 // Liberal parsing into node name, variable name and value.
1388 len = strcspn(line, "\t =");
1390 value += strspn(value, "\t ");
1393 value += strspn(value, "\t ");
1396 variable = strchr(line, '.');
1405 fprintf(stderr, "No variable given.\n");
1409 if(action >= 0 && !*value) {
1410 fprintf(stderr, "No value for variable given.\n");
1414 if(action < -1 && *value)
1417 /* Some simple checks. */
1419 bool warnonremove = false;
1421 for(int i = 0; variables[i].name; i++) {
1422 if(strcasecmp(variables[i].name, variable))
1426 variable = (char *)variables[i].name;
1428 /* Discourage use of obsolete variables. */
1430 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1432 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1434 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1439 /* Don't put server variables in host config files */
1441 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1443 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1445 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1450 /* Should this go into our own host config file? */
1452 if(!node && !(variables[i].type & VAR_SERVER)) {
1453 node = get_my_name(true);
1458 /* Change "add" into "set" for variables that do not allow multiple occurences.
1459 Turn on warnings when it seems variables might be removed unintentionally. */
1461 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1462 warnonremove = true;
1464 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1465 warnonremove = true;
1471 if(node && !check_id(node)) {
1472 fprintf(stderr, "Invalid name for node.\n");
1477 if(force || action < 0) {
1478 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1480 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1485 // Open the right configuration file.
1488 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1490 filename = tinc_conf;
1492 FILE *f = fopen(filename, "r");
1494 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1498 char *tmpfile = NULL;
1502 xasprintf(&tmpfile, "%s.config.tmp", filename);
1503 tf = fopen(tmpfile, "w");
1505 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1511 // Copy the file, making modifications on the fly, unless we are just getting a value.
1515 bool removed = false;
1518 while(fgets(buf1, sizeof buf1, f)) {
1519 buf1[sizeof buf1 - 1] = 0;
1520 strncpy(buf2, buf1, sizeof buf2);
1522 // Parse line in a simple way
1526 len = strcspn(buf2, "\t =");
1527 bvalue = buf2 + len;
1528 bvalue += strspn(bvalue, "\t ");
1529 if(*bvalue == '=') {
1531 bvalue += strspn(bvalue, "\t ");
1537 if(!strcasecmp(buf2, variable)) {
1541 printf("%s\n", bvalue);
1543 } else if(action == -1) {
1544 if(!*value || !strcasecmp(bvalue, value)) {
1549 } else if(action == 0) {
1550 // Warn if "set" was used for variables that can occur multiple times
1551 if(warnonremove && strcasecmp(bvalue, value))
1552 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1554 // Already set? Delete the rest...
1558 // Otherwise, replace.
1559 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1560 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1569 // Copy original line...
1570 if(fputs(buf1, tf) < 0) {
1571 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1575 // Add newline if it is missing...
1576 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1577 if(fputc('\n', tf) < 0) {
1578 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1585 // Make sure we read everything...
1586 if(ferror(f) || !feof(f)) {
1587 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1592 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1596 // Add new variable if necessary.
1597 if(action > 0 || (action == 0 && !set)) {
1598 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1599 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1606 fprintf(stderr, "No matching configuration variables found.\n");
1610 // Make sure we wrote everything...
1612 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1616 // Could we find what we had to remove?
1617 if(action < 0 && !removed) {
1619 fprintf(stderr, "No configuration variables deleted.\n");
1623 // Replace the configuration file with the new one
1625 if(remove(filename)) {
1626 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1630 if(rename(tmpfile, filename)) {
1631 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1635 // Silently try notifying a running tincd of changes.
1636 if(connect_tincd(false))
1637 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1642 bool check_id(const char *name) {
1646 for(int i = 0; i < strlen(name); i++) {
1647 if(!isalnum(name[i]) && name[i] != '_')
1654 static bool try_bind(int port) {
1655 struct addrinfo *ai = NULL;
1656 struct addrinfo hint = {
1657 .ai_flags = AI_PASSIVE,
1658 .ai_family = AF_UNSPEC,
1659 .ai_socktype = SOCK_STREAM,
1660 .ai_protocol = IPPROTO_TCP,
1664 snprintf(portstr, sizeof portstr, "%d", port);
1666 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1670 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1673 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1683 int check_port(char *name) {
1687 fprintf(stderr, "Warning: could not bind to port 655. ");
1689 for(int i = 0; i < 100; i++) {
1690 int port = 0x1000 + (rand() & 0x7fff);
1691 if(try_bind(port)) {
1693 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1694 FILE *f = fopen(filename, "a");
1697 fprintf(stderr, "Please change tinc's Port manually.\n");
1701 fprintf(f, "Port = %d\n", port);
1703 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1708 fprintf(stderr, "Please change tinc's Port manually.\n");
1712 static int cmd_init(int argc, char *argv[]) {
1713 if(!access(tinc_conf, F_OK)) {
1714 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1719 fprintf(stderr, "Too many arguments!\n");
1721 } else if(argc < 2) {
1724 fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1725 if(!fgets(buf, sizeof buf, stdin)) {
1726 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1729 int len = rstrip(buf);
1731 fprintf(stderr, "No name given!\n");
1736 fprintf(stderr, "No Name given!\n");
1740 name = strdup(argv[1]);
1742 fprintf(stderr, "No Name given!\n");
1747 if(!check_id(name)) {
1748 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1752 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1753 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1757 if(mkdir(confbase, 0777) && errno != EEXIST) {
1758 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1762 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1763 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1767 FILE *f = fopen(tinc_conf, "w");
1769 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1773 fprintf(f, "Name = %s\n", name);
1776 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1783 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1784 if(access(filename, F_OK)) {
1785 FILE *f = fopenmask(filename, "w", 0777);
1787 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1790 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");
1799 static int cmd_generate_keys(int argc, char *argv[]) {
1801 fprintf(stderr, "Too many arguments!\n");
1806 name = get_my_name(false);
1808 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1811 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1813 fprintf(stderr, "Too many arguments!\n");
1818 name = get_my_name(false);
1820 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1823 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1825 fprintf(stderr, "Too many arguments!\n");
1830 name = get_my_name(false);
1832 return !ecdsa_keygen(true);
1835 static int cmd_help(int argc, char *argv[]) {
1840 static int cmd_version(int argc, char *argv[]) {
1842 fprintf(stderr, "Too many arguments!\n");
1850 static int cmd_info(int argc, char *argv[]) {
1852 fprintf(stderr, "Invalid number of arguments.\n");
1856 if(!connect_tincd(true))
1859 return info(fd, argv[1]);
1862 static const char *conffiles[] = {
1873 static int cmd_edit(int argc, char *argv[]) {
1875 fprintf(stderr, "Invalid number of arguments.\n");
1879 char *filename = NULL;
1881 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1882 for(int i = 0; conffiles[i]; i++) {
1883 if(!strcmp(argv[1], conffiles[i])) {
1884 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1893 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1894 char *dash = strchr(argv[1], '-');
1897 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1898 fprintf(stderr, "Invalid configuration filename.\n");
1906 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1908 xasprintf(&command, "edit \"%s\"", filename);
1910 int result = system(command);
1914 // Silently try notifying a running tincd of changes.
1915 if(connect_tincd(false))
1916 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1921 static int export(const char *name, FILE *out) {
1923 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1924 FILE *in = fopen(filename, "r");
1926 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1930 fprintf(out, "Name = %s\n", name);
1932 while(fgets(buf, sizeof buf, in)) {
1933 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1938 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1947 static int cmd_export(int argc, char *argv[]) {
1949 fprintf(stderr, "Too many arguments!\n");
1953 char *name = get_my_name(true);
1957 int result = export(name, stdout);
1965 static int cmd_export_all(int argc, char *argv[]) {
1967 fprintf(stderr, "Too many arguments!\n");
1971 DIR *dir = opendir(hosts_dir);
1973 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1981 while((ent = readdir(dir))) {
1982 if(!check_id(ent->d_name))
1988 printf("#---------------------------------------------------------------#\n");
1990 result |= export(ent->d_name, stdout);
1999 static int cmd_import(int argc, char *argv[]) {
2001 fprintf(stderr, "Too many arguments!\n");
2010 char *filename = NULL;
2012 bool firstline = true;
2014 while(fgets(buf, sizeof buf, in)) {
2015 if(sscanf(buf, "Name = %s", name) == 1) {
2018 if(!check_id(name)) {
2019 fprintf(stderr, "Invalid Name in input!\n");
2027 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2029 if(!force && !access(filename, F_OK)) {
2030 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2035 out = fopen(filename, "w");
2037 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2043 } else if(firstline) {
2044 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2049 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2053 if(fputs(buf, out) < 0) {
2054 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2064 fprintf(stderr, "Imported %d host configuration files.\n", count);
2067 fprintf(stderr, "No host configuration files imported.\n");
2072 static int cmd_exchange(int argc, char *argv[]) {
2073 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2076 static int cmd_exchange_all(int argc, char *argv[]) {
2077 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2080 static int switch_network(char *name) {
2092 free(unixsocketname);
2093 unixsocketname = NULL;
2099 netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2102 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2103 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2104 xasprintf(&prompt, "%s> ", identname);
2109 static int cmd_network(int argc, char *argv[]) {
2111 fprintf(stderr, "Too many arguments!\n");
2116 return switch_network(argv[1]);
2118 DIR *dir = opendir(confdir);
2120 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2125 while((ent = readdir(dir))) {
2126 if(*ent->d_name == '.')
2129 if(!strcmp(ent->d_name, "tinc.conf")) {
2135 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2136 if(!access(fname, R_OK))
2137 printf("%s\n", ent->d_name);
2144 static const struct {
2145 const char *command;
2146 int (*function)(int argc, char *argv[]);
2149 {"start", cmd_start},
2151 {"restart", cmd_restart},
2152 {"reload", cmd_reload},
2154 {"purge", cmd_purge},
2155 {"debug", cmd_debug},
2156 {"retry", cmd_retry},
2157 {"connect", cmd_connect},
2158 {"disconnect", cmd_disconnect},
2163 {"config", cmd_config, true},
2164 {"add", cmd_config},
2165 {"del", cmd_config},
2166 {"get", cmd_config},
2167 {"set", cmd_config},
2169 {"generate-keys", cmd_generate_keys},
2170 {"generate-rsa-keys", cmd_generate_rsa_keys},
2171 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2173 {"version", cmd_version},
2176 {"export", cmd_export},
2177 {"export-all", cmd_export_all},
2178 {"import", cmd_import},
2179 {"exchange", cmd_exchange},
2180 {"exchange-all", cmd_exchange_all},
2181 {"invite", cmd_invite},
2183 {"network", cmd_network},
2187 #ifdef HAVE_READLINE
2188 static char *complete_command(const char *text, int state) {
2196 while(commands[i].command) {
2197 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2198 return xstrdup(commands[i].command);
2205 static char *complete_dump(const char *text, int state) {
2206 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2215 if(!strncasecmp(matches[i], text, strlen(text)))
2216 return xstrdup(matches[i]);
2223 static char *complete_config(const char *text, int state) {
2231 while(variables[i].name) {
2232 char *dot = strchr(text, '.');
2234 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2236 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2240 if(!strncasecmp(variables[i].name, text, strlen(text)))
2241 return xstrdup(variables[i].name);
2249 static char *complete_info(const char *text, int state) {
2253 if(!connect_tincd(false))
2255 // Check the list of nodes
2256 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2257 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2260 while(recvline(fd, line, sizeof line)) {
2262 int n = sscanf(line, "%d %d %s", &code, &req, item);
2272 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2276 if(!strncmp(item, text, strlen(text)))
2277 return xstrdup(strip_weight(item));
2283 static char *complete_nothing(const char *text, int state) {
2287 static char **completion (const char *text, int start, int end) {
2288 char **matches = NULL;
2291 matches = rl_completion_matches(text, complete_command);
2292 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2293 matches = rl_completion_matches(text, complete_dump);
2294 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2295 matches = rl_completion_matches(text, complete_config);
2296 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2297 matches = rl_completion_matches(text, complete_config);
2298 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2299 matches = rl_completion_matches(text, complete_config);
2300 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2301 matches = rl_completion_matches(text, complete_config);
2302 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2303 matches = rl_completion_matches(text, complete_info);
2309 static int cmd_shell(int argc, char *argv[]) {
2310 xasprintf(&prompt, "%s> ", identname);
2314 int maxargs = argc + 16;
2315 char **nargv = xmalloc(maxargs * sizeof *nargv);
2317 for(int i = 0; i < argc; i++)
2320 #ifdef HAVE_READLINE
2321 rl_readline_name = "tinc";
2322 rl_completion_entry_function = complete_nothing;
2323 rl_attempted_completion_function = completion;
2324 rl_filename_completion_desired = 0;
2329 #ifdef HAVE_READLINE
2333 rl_basic_word_break_characters = "\t\n ";
2334 line = readline(prompt);
2336 copy = xstrdup(line);
2338 line = fgets(buf, sizeof buf, stdin);
2342 fputs(prompt, stdout);
2344 line = fgets(buf, sizeof buf, stdin);
2350 /* Ignore comments */
2358 char *p = line + strspn(line, " \t\n");
2359 char *next = strtok(p, " \t\n");
2362 if(nargc >= maxargs) {
2363 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2366 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2371 next = strtok(NULL, " \t\n");
2377 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2382 for(int i = 0; commands[i].command; i++) {
2383 if(!strcasecmp(nargv[argc], commands[i].command)) {
2384 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2390 #ifdef HAVE_READLINE
2396 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2409 int main(int argc, char *argv[]) {
2410 program_name = argv[0];
2414 if(!parse_options(argc, argv))
2418 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2419 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2432 static struct WSAData wsa_state;
2434 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2435 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2443 tty = isatty(0) && isatty(1);
2446 return cmd_shell(argc, argv);
2448 for(int i = 0; commands[i].command; i++) {
2449 if(!strcasecmp(argv[optind], commands[i].command))
2450 return commands[i].function(argc - optind, argv + optind);
2453 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);