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"
42 static char **orig_argv;
45 /* If nonzero, display usage information and exit. */
46 static bool show_help = false;
48 /* If nonzero, print the version on standard output and exit. */
49 static bool show_version = false;
51 static char *name = NULL;
52 static char controlcookie[1025];
53 char *tinc_conf = NULL;
54 char *hosts_dir = NULL;
57 // Horrible global variables...
64 static bool force = false;
66 bool confbasegiven = false;
67 bool netnamegiven = false;
68 char *scriptinterpreter = NULL;
69 char *scriptextension = "";
72 static struct option const long_options[] = {
73 {"config", required_argument, NULL, 'c'},
74 {"net", required_argument, NULL, 'n'},
75 {"help", no_argument, NULL, 1},
76 {"version", no_argument, NULL, 2},
77 {"pidfile", required_argument, NULL, 3},
78 {"force", no_argument, NULL, 4},
82 static void version(void) {
83 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
84 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
85 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
86 "See the AUTHORS file for a complete list.\n\n"
87 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
88 "and you are welcome to redistribute it under certain conditions;\n"
89 "see the file COPYING for details.\n");
92 static void usage(bool status) {
94 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
96 printf("Usage: %s [options] command\n\n", program_name);
97 printf("Valid options are:\n"
98 " -c, --config=DIR Read configuration options from DIR.\n"
99 " -n, --net=NETNAME Connect to net NETNAME.\n"
100 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
101 " --help Display this help and exit.\n"
102 " --version Output version information and exit.\n"
104 "Valid commands are:\n"
105 " init [name] Create initial configuration files.\n"
106 " get VARIABLE Print current value of VARIABLE\n"
107 " set VARIABLE VALUE Set VARIABLE to VALUE\n"
108 " add VARIABLE VALUE Add VARIABLE with the given VALUE\n"
109 " del VARIABLE [VALUE] Remove VARIABLE [only ones with watching VALUE]\n"
110 " start [tincd options] Start tincd.\n"
111 " stop Stop tincd.\n"
112 " restart [tincd options] Restart tincd.\n"
113 " reload Partially reload configuration of running tincd.\n"
114 " pid Show PID of currently running tincd.\n"
115 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
116 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
117 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
118 " dump Dump a list of one of the following things:\n"
119 " [reachable] nodes - all known nodes in the VPN\n"
120 " edges - all known connections in the VPN\n"
121 " subnets - all known subnets in the VPN\n"
122 " connections - all meta connections with ourself\n"
123 " [di]graph - graph of the VPN in dotty format\n"
124 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
125 " purge Purge unreachable nodes\n"
126 " debug N Set debug level\n"
127 " retry Retry all outgoing connections\n"
128 " disconnect NODE Close meta connection with NODE\n"
130 " top Show real-time statistics\n"
132 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
133 " log [level] Dump log output [up to the specified level]\n"
134 " export Export host configuration of local node to standard output\n"
135 " export-all Export all host configuration files to standard output\n"
136 " import [--force] Import host configuration file(s) from standard input\n"
137 " exchange [--force] Same as export followed by import\n"
138 " exchange-all [--force] Same as export-all followed by import\n"
139 " invite NODE [...] Generate an invitation for NODE\n"
140 " join INVITATION Join a VPN using an INVITIATION\n"
141 " network [NETNAME] List all known networks, or switch to the one named NETNAME.\n"
143 printf("Report bugs to tinc@tinc-vpn.org.\n");
147 static bool parse_options(int argc, char **argv) {
149 int option_index = 0;
151 while((r = getopt_long(argc, argv, "+c:n:", long_options, &option_index)) != EOF) {
153 case 0: /* long option */
156 case 'c': /* config file */
157 confbase = xstrdup(optarg);
158 confbasegiven = true;
161 case 'n': /* net name given */
162 netname = xstrdup(optarg);
165 case 1: /* show help */
169 case 2: /* show version */
173 case 3: /* open control socket here */
174 pidfilename = xstrdup(optarg);
181 case '?': /* wrong options */
190 if(!netname && (netname = getenv("NETNAME")))
191 netname = xstrdup(netname);
193 /* netname "." is special: a "top-level name" */
195 if(netname && (!*netname || !strcmp(netname, "."))) {
200 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
201 fprintf(stderr, "Invalid character in netname!\n");
208 /* Open a file with the desired permissions, minus the umask.
209 Also, if we want to create an executable file, we call fchmod()
210 to set the executable bits. */
212 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
213 mode_t mask = umask(0);
216 FILE *f = fopen(filename, mode);
218 if((perms & 0444) && f)
219 fchmod(fileno(f), perms);
225 static void disable_old_keys(const char *filename, const char *what) {
226 char tmpfile[PATH_MAX] = "";
228 bool disabled = false;
233 r = fopen(filename, "r");
237 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
239 struct stat st = {.st_mode = 0600};
240 fstat(fileno(r), &st);
241 w = fopenmask(tmpfile, "w", st.st_mode);
243 while(fgets(buf, sizeof buf, r)) {
244 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
245 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
251 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
257 if(block || ecdsapubkey)
259 if(fputs(buf, w) < 0) {
265 if(block && !strncmp(buf, "-----END ", 9))
272 if(ferror(r) || fclose(r) < 0)
277 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
284 // We cannot atomically replace files on Windows.
285 char bakfile[PATH_MAX] = "";
286 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
287 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
288 rename(bakfile, filename);
290 if(rename(tmpfile, filename)) {
292 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
297 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
304 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask, mode_t perms) {
310 /* Check stdin and stdout */
312 /* Ask for a file and/or directory name. */
313 fprintf(stderr, "Please enter a file to save %s to [%s]: ", what, filename);
315 if(fgets(buf, sizeof buf, stdin) == NULL) {
316 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
320 size_t len = strlen(buf);
329 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
331 if(filename[0] != '/') {
333 /* The directory is a relative path or a filename. */
334 directory = get_current_dir_name();
335 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
339 disable_old_keys(filename, what);
341 /* Open it first to keep the inode busy */
343 r = fopenmask(filename, mode, perms);
346 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
354 Generate a public/private ECDSA keypair, and ask for a file to store
357 static bool ecdsa_keygen(bool ask) {
360 char *pubname, *privname;
362 fprintf(stderr, "Generating ECDSA keypair:\n");
364 if(!(key = ecdsa_generate())) {
365 fprintf(stderr, "Error during key generation!\n");
368 fprintf(stderr, "Done.\n");
370 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
371 f = ask_and_open(privname, "private ECDSA key", "a", ask, 0600);
377 if(!ecdsa_write_pem_private_key(key, f)) {
378 fprintf(stderr, "Error writing private key!\n");
387 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
389 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
391 f = ask_and_open(pubname, "public ECDSA key", "a", ask, 0666);
397 char *pubkey = ecdsa_get_base64_public_key(key);
398 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
408 Generate a public/private RSA keypair, and ask for a file to store
411 static bool rsa_keygen(int bits, bool ask) {
414 char *pubname, *privname;
416 fprintf(stderr, "Generating %d bits keys:\n", bits);
418 if(!(key = rsa_generate(bits, 0x10001))) {
419 fprintf(stderr, "Error during key generation!\n");
422 fprintf(stderr, "Done.\n");
424 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
425 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
431 if(!rsa_write_pem_private_key(key, f)) {
432 fprintf(stderr, "Error writing private key!\n");
441 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
443 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
445 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
451 if(!rsa_write_pem_public_key(key, f)) {
452 fprintf(stderr, "Error writing public key!\n");
467 bool recvline(int fd, char *line, size_t len) {
468 char *newline = NULL;
473 while(!(newline = memchr(buffer, '\n', blen))) {
474 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
475 if(result == -1 && errno == EINTR)
482 if(newline - buffer >= len)
485 len = newline - buffer;
487 memcpy(line, buffer, len);
489 memmove(buffer, newline + 1, blen - len - 1);
495 bool recvdata(int fd, char *data, size_t len) {
500 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
501 if(result == -1 && errno == EINTR)
508 memcpy(data, buffer, len);
509 memmove(buffer, buffer + len, blen - len);
515 bool sendline(int fd, char *format, ...) {
516 static char buffer[4096];
521 va_start(ap, format);
522 blen = vsnprintf(buffer, sizeof buffer, format, ap);
525 if(blen < 1 || blen >= sizeof buffer)
532 int result = send(fd, p, blen, 0);
533 if(result == -1 && errno == EINTR)
544 static void pcap(int fd, FILE *out, int snaplen) {
545 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
553 uint32_t tz_accuracy;
560 snaplen ?: sizeof data,
573 fwrite(&header, sizeof header, 1, out);
577 while(recvline(fd, line, sizeof line)) {
579 int n = sscanf(line, "%d %d %d", &code, &req, &len);
580 gettimeofday(&tv, NULL);
581 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
583 if(!recvdata(fd, data, len))
585 packet.tv_sec = tv.tv_sec;
586 packet.tv_usec = tv.tv_usec;
588 packet.origlen = len;
589 fwrite(&packet, sizeof packet, 1, out);
590 fwrite(data, len, 1, out);
595 static void logcontrol(int fd, FILE *out, int level) {
596 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
600 while(recvline(fd, line, sizeof line)) {
602 int n = sscanf(line, "%d %d %d", &code, &req, &len);
603 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
605 if(!recvdata(fd, data, len))
607 fwrite(data, len, 1, out);
614 static bool remove_service(void) {
615 SC_HANDLE manager = NULL;
616 SC_HANDLE service = NULL;
617 SERVICE_STATUS status = {0};
619 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
621 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
625 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
628 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
632 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
633 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
635 fprintf(stderr, "%s service stopped\n", identname);
637 if(!DeleteService(service)) {
638 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
642 fprintf(stderr, "%s service removed\n", identname);
648 bool connect_tincd(bool verbose) {
653 struct timeval tv = {0, 0};
654 if(select(fd + 1, &r, NULL, NULL, &tv)) {
655 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
663 FILE *f = fopen(pidfilename, "r");
666 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
673 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
675 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
683 struct sockaddr_un sa;
684 sa.sun_family = AF_UNIX;
685 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
687 fd = socket(AF_UNIX, SOCK_STREAM, 0);
690 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
694 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
696 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
702 struct addrinfo hints = {
703 .ai_family = AF_UNSPEC,
704 .ai_socktype = SOCK_STREAM,
705 .ai_protocol = IPPROTO_TCP,
709 struct addrinfo *res = NULL;
711 if(getaddrinfo(host, port, &hints, &res) || !res) {
713 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
717 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
720 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
725 unsigned long arg = 0;
727 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
729 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
733 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
735 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
747 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
749 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
755 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
757 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
759 fprintf(stderr, "Could not fully establish control socket connection\n");
769 static int cmd_start(int argc, char *argv[]) {
770 if(connect_tincd(false)) {
772 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
774 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
779 char *slash = strrchr(program_name, '/');
782 if ((c = strrchr(program_name, '\\')) > slash)
787 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
792 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
795 for(int i = 1; i < optind; i++)
796 nargv[nargc++] = orig_argv[i];
797 for(int i = 1; i < argc; i++)
798 nargv[nargc++] = argv[i];
802 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
807 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
813 exit(execvp(c, nargv));
817 int status = -1, result;
819 signal(SIGINT, SIG_IGN);
821 result = waitpid(pid, &status, 0);
823 signal(SIGINT, SIG_DFL);
826 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
827 fprintf(stderr, "Error starting %s\n", c);
835 static int cmd_stop(int argc, char *argv[]) {
837 fprintf(stderr, "Too many arguments!\n");
842 if(!connect_tincd(true)) {
844 if(kill(pid, SIGTERM)) {
845 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
849 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
850 waitpid(pid, NULL, 0);
857 sendline(fd, "%d %d", CONTROL, REQ_STOP);
859 while(recvline(fd, line, sizeof line)) {
860 // Wait for tincd to close the connection...
863 if(!remove_service())
873 static int cmd_restart(int argc, char *argv[]) {
875 return cmd_start(argc, argv);
878 static int cmd_reload(int argc, char *argv[]) {
880 fprintf(stderr, "Too many arguments!\n");
884 if(!connect_tincd(true))
887 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
888 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
889 fprintf(stderr, "Could not reload configuration.\n");
897 static int cmd_dump(int argc, char *argv[]) {
898 bool only_reachable = false;
900 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
901 if(strcasecmp(argv[2], "nodes")) {
902 fprintf(stderr, "`reachable' only supported for nodes.\n");
906 only_reachable = true;
912 fprintf(stderr, "Invalid number of arguments.\n");
917 if(!connect_tincd(true))
922 if(!strcasecmp(argv[1], "nodes"))
923 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
924 else if(!strcasecmp(argv[1], "edges"))
925 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
926 else if(!strcasecmp(argv[1], "subnets"))
927 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
928 else if(!strcasecmp(argv[1], "connections"))
929 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
930 else if(!strcasecmp(argv[1], "graph")) {
931 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
932 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
934 } else if(!strcasecmp(argv[1], "digraph")) {
935 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
936 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
939 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
946 else if(do_graph == 2)
947 printf("digraph {\n");
949 while(recvline(fd, line, sizeof line)) {
950 char node1[4096], node2[4096];
951 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
953 if(do_graph && req == REQ_DUMP_NODES)
972 int cipher, digest, maclength, compression, distance, socket, weight;
973 short int pmtu, minmtu, maxmtu;
974 unsigned int options, status_int;
975 node_status_t status;
976 long int last_state_change;
979 case REQ_DUMP_NODES: {
980 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);
982 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
986 memcpy(&status, &status_int, sizeof status);
989 const char *color = "black";
990 if(!strcmp(host, "MYSELF"))
992 else if(!status.reachable)
994 else if(strcmp(via, node))
996 else if(!status.validkey)
1000 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1002 if(only_reachable && !status.reachable)
1004 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",
1005 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1009 case REQ_DUMP_EDGES: {
1010 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1012 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1017 float w = 1 + 65536.0 / weight;
1018 if(do_graph == 1 && strcmp(node1, node2) > 0)
1019 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1020 else if(do_graph == 2)
1021 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1023 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1027 case REQ_DUMP_SUBNETS: {
1028 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1030 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1033 printf("%s owner %s\n", strip_weight(subnet), node);
1036 case REQ_DUMP_CONNECTIONS: {
1037 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1039 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1042 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1046 fprintf(stderr, "Unable to parse dump from tincd.\n");
1051 fprintf(stderr, "Error receiving dump.\n");
1055 static int cmd_purge(int argc, char *argv[]) {
1057 fprintf(stderr, "Too many arguments!\n");
1061 if(!connect_tincd(true))
1064 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1065 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1066 fprintf(stderr, "Could not purge old information.\n");
1073 static int cmd_debug(int argc, char *argv[]) {
1075 fprintf(stderr, "Invalid number of arguments.\n");
1079 if(!connect_tincd(true))
1082 int debuglevel = atoi(argv[1]);
1085 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1086 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1087 fprintf(stderr, "Could not set debug level.\n");
1091 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1095 static int cmd_retry(int argc, char *argv[]) {
1097 fprintf(stderr, "Too many arguments!\n");
1101 if(!connect_tincd(true))
1104 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1105 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1106 fprintf(stderr, "Could not retry outgoing connections.\n");
1113 static int cmd_connect(int argc, char *argv[]) {
1115 fprintf(stderr, "Invalid number of arguments.\n");
1119 if(!check_id(argv[1])) {
1120 fprintf(stderr, "Invalid name for node.\n");
1124 if(!connect_tincd(true))
1127 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1128 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1129 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1136 static int cmd_disconnect(int argc, char *argv[]) {
1138 fprintf(stderr, "Invalid number of arguments.\n");
1142 if(!check_id(argv[1])) {
1143 fprintf(stderr, "Invalid name for node.\n");
1147 if(!connect_tincd(true))
1150 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1151 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1152 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1159 static int cmd_top(int argc, char *argv[]) {
1161 fprintf(stderr, "Too many arguments!\n");
1166 if(!connect_tincd(true))
1172 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1177 static int cmd_pcap(int argc, char *argv[]) {
1179 fprintf(stderr, "Too many arguments!\n");
1183 if(!connect_tincd(true))
1186 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1191 static void sigint_handler(int sig) {
1192 fprintf(stderr, "\n");
1193 shutdown(fd, SHUT_RDWR);
1197 static int cmd_log(int argc, char *argv[]) {
1199 fprintf(stderr, "Too many arguments!\n");
1203 if(!connect_tincd(true))
1207 signal(SIGINT, sigint_handler);
1210 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1213 signal(SIGINT, SIG_DFL);
1221 static int cmd_pid(int argc, char *argv[]) {
1223 fprintf(stderr, "Too many arguments!\n");
1227 if(!connect_tincd(true) && !pid)
1230 printf("%d\n", pid);
1234 int rstrip(char *value) {
1235 int len = strlen(value);
1236 while(len && strchr("\t\r\n ", value[len - 1]))
1241 char *get_my_name(bool verbose) {
1242 FILE *f = fopen(tinc_conf, "r");
1245 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1251 while(fgets(buf, sizeof buf, f)) {
1252 int len = strcspn(buf, "\t =");
1254 value += strspn(value, "\t ");
1257 value += strspn(value, "\t ");
1262 if(strcasecmp(buf, "Name"))
1266 return strdup(value);
1272 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1276 const var_t variables[] = {
1277 /* Server configuration */
1278 {"AddressFamily", VAR_SERVER},
1279 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1280 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1281 {"BindToInterface", VAR_SERVER},
1282 {"Broadcast", VAR_SERVER | VAR_SAFE},
1283 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1284 {"DecrementTTL", VAR_SERVER},
1285 {"Device", VAR_SERVER},
1286 {"DeviceType", VAR_SERVER},
1287 {"DirectOnly", VAR_SERVER},
1288 {"ECDSAPrivateKeyFile", VAR_SERVER},
1289 {"ExperimentalProtocol", VAR_SERVER},
1290 {"Forwarding", VAR_SERVER},
1291 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1292 {"Hostnames", VAR_SERVER},
1293 {"IffOneQueue", VAR_SERVER},
1294 {"Interface", VAR_SERVER},
1295 {"KeyExpire", VAR_SERVER},
1296 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1297 {"LocalDiscovery", VAR_SERVER},
1298 {"MACExpire", VAR_SERVER},
1299 {"MaxConnectionBurst", VAR_SERVER},
1300 {"MaxOutputBufferSize", VAR_SERVER},
1301 {"MaxTimeout", VAR_SERVER},
1302 {"Mode", VAR_SERVER | VAR_SAFE},
1303 {"Name", VAR_SERVER},
1304 {"PingInterval", VAR_SERVER},
1305 {"PingTimeout", VAR_SERVER},
1306 {"PriorityInheritance", VAR_SERVER},
1307 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1308 {"PrivateKeyFile", VAR_SERVER},
1309 {"ProcessPriority", VAR_SERVER},
1310 {"Proxy", VAR_SERVER},
1311 {"ReplayWindow", VAR_SERVER},
1312 {"ScriptsExtension", VAR_SERVER},
1313 {"ScriptsInterpreter", VAR_SERVER},
1314 {"StrictSubnets", VAR_SERVER},
1315 {"TunnelServer", VAR_SERVER},
1316 {"UDPRcvBuf", VAR_SERVER},
1317 {"UDPSndBuf", VAR_SERVER},
1318 {"VDEGroup", VAR_SERVER},
1319 {"VDEPort", VAR_SERVER},
1320 /* Host configuration */
1321 {"Address", VAR_HOST | VAR_MULTIPLE},
1322 {"Cipher", VAR_SERVER | VAR_HOST},
1323 {"ClampMSS", VAR_SERVER | VAR_HOST},
1324 {"Compression", VAR_SERVER | VAR_HOST},
1325 {"Digest", VAR_SERVER | VAR_HOST},
1326 {"ECDSAPublicKey", VAR_HOST},
1327 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1328 {"IndirectData", VAR_SERVER | VAR_HOST},
1329 {"MACLength", VAR_SERVER | VAR_HOST},
1330 {"PMTU", VAR_SERVER | VAR_HOST},
1331 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1333 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1334 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1335 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1336 {"TCPOnly", VAR_SERVER | VAR_HOST},
1337 {"Weight", VAR_HOST | VAR_SAFE},
1341 static int cmd_config(int argc, char *argv[]) {
1343 fprintf(stderr, "Invalid number of arguments.\n");
1347 if(strcasecmp(argv[0], "config"))
1351 if(!strcasecmp(argv[1], "get")) {
1353 } else if(!strcasecmp(argv[1], "add")) {
1354 argv++, argc--, action = 1;
1355 } else if(!strcasecmp(argv[1], "del")) {
1356 argv++, argc--, action = -1;
1357 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1358 argv++, argc--, action = 0;
1362 fprintf(stderr, "Invalid number of arguments.\n");
1366 // Concatenate the rest of the command line
1367 strncpy(line, argv[1], sizeof line - 1);
1368 for(int i = 2; i < argc; i++) {
1369 strncat(line, " ", sizeof line - 1 - strlen(line));
1370 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1373 // Liberal parsing into node name, variable name and value.
1379 len = strcspn(line, "\t =");
1381 value += strspn(value, "\t ");
1384 value += strspn(value, "\t ");
1387 variable = strchr(line, '.');
1396 fprintf(stderr, "No variable given.\n");
1400 if(action >= 0 && !*value) {
1401 fprintf(stderr, "No value for variable given.\n");
1405 if(action < -1 && *value)
1408 /* Some simple checks. */
1410 bool warnonremove = false;
1412 for(int i = 0; variables[i].name; i++) {
1413 if(strcasecmp(variables[i].name, variable))
1417 variable = (char *)variables[i].name;
1419 /* Discourage use of obsolete variables. */
1421 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1423 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1425 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1430 /* Don't put server variables in host config files */
1432 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1434 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1436 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1441 /* Should this go into our own host config file? */
1443 if(!node && !(variables[i].type & VAR_SERVER)) {
1444 node = get_my_name(true);
1449 /* Change "add" into "set" for variables that do not allow multiple occurences.
1450 Turn on warnings when it seems variables might be removed unintentionally. */
1452 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1453 warnonremove = true;
1455 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1456 warnonremove = true;
1462 if(node && !check_id(node)) {
1463 fprintf(stderr, "Invalid name for node.\n");
1468 if(force || action < 0) {
1469 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1471 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1476 // Open the right configuration file.
1479 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1481 filename = tinc_conf;
1483 FILE *f = fopen(filename, "r");
1485 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1489 char *tmpfile = NULL;
1493 xasprintf(&tmpfile, "%s.config.tmp", filename);
1494 tf = fopen(tmpfile, "w");
1496 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1502 // Copy the file, making modifications on the fly, unless we are just getting a value.
1506 bool removed = false;
1509 while(fgets(buf1, sizeof buf1, f)) {
1510 buf1[sizeof buf1 - 1] = 0;
1511 strncpy(buf2, buf1, sizeof buf2);
1513 // Parse line in a simple way
1517 len = strcspn(buf2, "\t =");
1518 bvalue = buf2 + len;
1519 bvalue += strspn(bvalue, "\t ");
1520 if(*bvalue == '=') {
1522 bvalue += strspn(bvalue, "\t ");
1528 if(!strcasecmp(buf2, variable)) {
1532 printf("%s\n", bvalue);
1534 } else if(action == -1) {
1535 if(!*value || !strcasecmp(bvalue, value)) {
1540 } else if(action == 0) {
1541 // Warn if "set" was used for variables that can occur multiple times
1542 if(warnonremove && strcasecmp(bvalue, value))
1543 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1545 // Already set? Delete the rest...
1549 // Otherwise, replace.
1550 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1551 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1560 // Copy original line...
1561 if(fputs(buf1, tf) < 0) {
1562 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1566 // Add newline if it is missing...
1567 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1568 if(fputc('\n', tf) < 0) {
1569 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1576 // Make sure we read everything...
1577 if(ferror(f) || !feof(f)) {
1578 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1583 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1587 // Add new variable if necessary.
1588 if(action > 0 || (action == 0 && !set)) {
1589 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1590 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1597 fprintf(stderr, "No matching configuration variables found.\n");
1601 // Make sure we wrote everything...
1603 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1607 // Could we find what we had to remove?
1608 if(action < 0 && !removed) {
1610 fprintf(stderr, "No configuration variables deleted.\n");
1614 // Replace the configuration file with the new one
1616 if(remove(filename)) {
1617 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1621 if(rename(tmpfile, filename)) {
1622 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1626 // Silently try notifying a running tincd of changes.
1627 if(connect_tincd(false))
1628 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1633 bool check_id(const char *name) {
1637 for(int i = 0; i < strlen(name); i++) {
1638 if(!isalnum(name[i]) && name[i] != '_')
1645 static bool try_bind(int port) {
1646 struct addrinfo *ai = NULL;
1647 struct addrinfo hint = {
1648 .ai_flags = AI_PASSIVE,
1649 .ai_family = AF_UNSPEC,
1650 .ai_socktype = SOCK_STREAM,
1651 .ai_protocol = IPPROTO_TCP,
1655 snprintf(portstr, sizeof portstr, "%d", port);
1657 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1661 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1664 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1674 int check_port(char *name) {
1678 fprintf(stderr, "Warning: could not bind to port 655. ");
1680 for(int i = 0; i < 100; i++) {
1681 int port = 0x1000 + (rand() & 0x7fff);
1682 if(try_bind(port)) {
1684 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1685 FILE *f = fopen(filename, "a");
1688 fprintf(stderr, "Please change tinc's Port manually.\n");
1692 fprintf(f, "Port = %d\n", port);
1694 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1699 fprintf(stderr, "Please change tinc's Port manually.\n");
1703 static int cmd_init(int argc, char *argv[]) {
1704 if(!access(tinc_conf, F_OK)) {
1705 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1710 fprintf(stderr, "Too many arguments!\n");
1712 } else if(argc < 2) {
1715 fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1716 if(!fgets(buf, sizeof buf, stdin)) {
1717 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1720 int len = rstrip(buf);
1722 fprintf(stderr, "No name given!\n");
1727 fprintf(stderr, "No Name given!\n");
1731 name = strdup(argv[1]);
1733 fprintf(stderr, "No Name given!\n");
1738 if(!check_id(name)) {
1739 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1743 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1744 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1748 if(mkdir(confbase, 0777) && errno != EEXIST) {
1749 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1753 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1754 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1758 FILE *f = fopen(tinc_conf, "w");
1760 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1764 fprintf(f, "Name = %s\n", name);
1767 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1774 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1775 if(access(filename, F_OK)) {
1776 FILE *f = fopenmask(filename, "w", 0777);
1778 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1781 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");
1790 static int cmd_generate_keys(int argc, char *argv[]) {
1792 fprintf(stderr, "Too many arguments!\n");
1797 name = get_my_name(false);
1799 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1802 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1804 fprintf(stderr, "Too many arguments!\n");
1809 name = get_my_name(false);
1811 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1814 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1816 fprintf(stderr, "Too many arguments!\n");
1821 name = get_my_name(false);
1823 return !ecdsa_keygen(true);
1826 static int cmd_help(int argc, char *argv[]) {
1831 static int cmd_version(int argc, char *argv[]) {
1833 fprintf(stderr, "Too many arguments!\n");
1841 static int cmd_info(int argc, char *argv[]) {
1843 fprintf(stderr, "Invalid number of arguments.\n");
1847 if(!connect_tincd(true))
1850 return info(fd, argv[1]);
1853 static const char *conffiles[] = {
1864 static int cmd_edit(int argc, char *argv[]) {
1866 fprintf(stderr, "Invalid number of arguments.\n");
1870 char *filename = NULL;
1872 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1873 for(int i = 0; conffiles[i]; i++) {
1874 if(!strcmp(argv[1], conffiles[i])) {
1875 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1884 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1885 char *dash = strchr(argv[1], '-');
1888 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1889 fprintf(stderr, "Invalid configuration filename.\n");
1897 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1899 xasprintf(&command, "edit \"%s\"", filename);
1901 int result = system(command);
1905 // Silently try notifying a running tincd of changes.
1906 if(connect_tincd(false))
1907 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1912 static int export(const char *name, FILE *out) {
1914 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1915 FILE *in = fopen(filename, "r");
1917 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1921 fprintf(out, "Name = %s\n", name);
1923 while(fgets(buf, sizeof buf, in)) {
1924 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1929 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1938 static int cmd_export(int argc, char *argv[]) {
1940 fprintf(stderr, "Too many arguments!\n");
1944 char *name = get_my_name(true);
1948 int result = export(name, stdout);
1956 static int cmd_export_all(int argc, char *argv[]) {
1958 fprintf(stderr, "Too many arguments!\n");
1962 DIR *dir = opendir(hosts_dir);
1964 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1972 while((ent = readdir(dir))) {
1973 if(!check_id(ent->d_name))
1979 printf("#---------------------------------------------------------------#\n");
1981 result |= export(ent->d_name, stdout);
1990 static int cmd_import(int argc, char *argv[]) {
1992 fprintf(stderr, "Too many arguments!\n");
2001 char *filename = NULL;
2003 bool firstline = true;
2005 while(fgets(buf, sizeof buf, in)) {
2006 if(sscanf(buf, "Name = %s", name) == 1) {
2009 if(!check_id(name)) {
2010 fprintf(stderr, "Invalid Name in input!\n");
2018 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2020 if(!force && !access(filename, F_OK)) {
2021 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2026 out = fopen(filename, "w");
2028 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2034 } else if(firstline) {
2035 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2040 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2044 if(fputs(buf, out) < 0) {
2045 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2055 fprintf(stderr, "Imported %d host configuration files.\n", count);
2058 fprintf(stderr, "No host configuration files imported.\n");
2063 static int cmd_exchange(int argc, char *argv[]) {
2064 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2067 static int cmd_exchange_all(int argc, char *argv[]) {
2068 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2071 static int switch_network(char *name) {
2083 free(unixsocketname);
2084 unixsocketname = NULL;
2090 netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2093 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2094 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2095 xasprintf(&prompt, "%s> ", identname);
2100 static int cmd_network(int argc, char *argv[]) {
2102 fprintf(stderr, "Too many arguments!\n");
2107 return switch_network(argv[1]);
2109 DIR *dir = opendir(confdir);
2111 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2116 while((ent = readdir(dir))) {
2117 if(*ent->d_name == '.')
2120 if(!strcmp(ent->d_name, "tinc.conf")) {
2126 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2127 if(!access(fname, R_OK))
2128 printf("%s\n", ent->d_name);
2135 static const struct {
2136 const char *command;
2137 int (*function)(int argc, char *argv[]);
2140 {"start", cmd_start},
2142 {"restart", cmd_restart},
2143 {"reload", cmd_reload},
2145 {"purge", cmd_purge},
2146 {"debug", cmd_debug},
2147 {"retry", cmd_retry},
2148 {"connect", cmd_connect},
2149 {"disconnect", cmd_disconnect},
2154 {"config", cmd_config, true},
2155 {"add", cmd_config},
2156 {"del", cmd_config},
2157 {"get", cmd_config},
2158 {"set", cmd_config},
2160 {"generate-keys", cmd_generate_keys},
2161 {"generate-rsa-keys", cmd_generate_rsa_keys},
2162 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2164 {"version", cmd_version},
2167 {"export", cmd_export},
2168 {"export-all", cmd_export_all},
2169 {"import", cmd_import},
2170 {"exchange", cmd_exchange},
2171 {"exchange-all", cmd_exchange_all},
2172 {"invite", cmd_invite},
2174 {"network", cmd_network},
2178 #ifdef HAVE_READLINE
2179 static char *complete_command(const char *text, int state) {
2187 while(commands[i].command) {
2188 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2189 return xstrdup(commands[i].command);
2196 static char *complete_dump(const char *text, int state) {
2197 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2206 if(!strncasecmp(matches[i], text, strlen(text)))
2207 return xstrdup(matches[i]);
2214 static char *complete_config(const char *text, int state) {
2222 while(variables[i].name) {
2223 char *dot = strchr(text, '.');
2225 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2227 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2231 if(!strncasecmp(variables[i].name, text, strlen(text)))
2232 return xstrdup(variables[i].name);
2240 static char *complete_info(const char *text, int state) {
2244 if(!connect_tincd(false))
2246 // Check the list of nodes
2247 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2248 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2251 while(recvline(fd, line, sizeof line)) {
2253 int n = sscanf(line, "%d %d %s", &code, &req, item);
2263 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2267 if(!strncmp(item, text, strlen(text)))
2268 return xstrdup(strip_weight(item));
2274 static char *complete_nothing(const char *text, int state) {
2278 static char **completion (const char *text, int start, int end) {
2279 char **matches = NULL;
2282 matches = rl_completion_matches(text, complete_command);
2283 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2284 matches = rl_completion_matches(text, complete_dump);
2285 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2286 matches = rl_completion_matches(text, complete_config);
2287 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2288 matches = rl_completion_matches(text, complete_config);
2289 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2290 matches = rl_completion_matches(text, complete_config);
2291 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2292 matches = rl_completion_matches(text, complete_config);
2293 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2294 matches = rl_completion_matches(text, complete_info);
2300 static int cmd_shell(int argc, char *argv[]) {
2301 xasprintf(&prompt, "%s> ", identname);
2305 int maxargs = argc + 16;
2306 char **nargv = xmalloc(maxargs * sizeof *nargv);
2308 for(int i = 0; i < argc; i++)
2311 #ifdef HAVE_READLINE
2312 rl_readline_name = "tinc";
2313 rl_completion_entry_function = complete_nothing;
2314 rl_attempted_completion_function = completion;
2315 rl_filename_completion_desired = 0;
2320 #ifdef HAVE_READLINE
2324 rl_basic_word_break_characters = "\t\n ";
2325 line = readline(prompt);
2327 copy = xstrdup(line);
2329 line = fgets(buf, sizeof buf, stdin);
2333 fputs(prompt, stdout);
2335 line = fgets(buf, sizeof buf, stdin);
2341 /* Ignore comments */
2349 char *p = line + strspn(line, " \t\n");
2350 char *next = strtok(p, " \t\n");
2353 if(nargc >= maxargs) {
2354 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2357 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2362 next = strtok(NULL, " \t\n");
2368 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2373 for(int i = 0; commands[i].command; i++) {
2374 if(!strcasecmp(nargv[argc], commands[i].command)) {
2375 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2381 #ifdef HAVE_READLINE
2387 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2400 int main(int argc, char *argv[]) {
2401 program_name = argv[0];
2405 if(!parse_options(argc, argv))
2409 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2410 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2423 static struct WSAData wsa_state;
2425 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2426 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2434 tty = isatty(0) && isatty(1);
2437 return cmd_shell(argc, argv);
2439 for(int i = 0; commands[i].command; i++) {
2440 if(!strcasecmp(argv[optind], commands[i].command))
2441 return commands[i].function(argc - optind, argv + optind);
2444 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);