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 Ed25519 public/private keypairs.\n"
120 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
121 " generate-ed25519-keys Generate a new Ed25519 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, " ED25519 ") && strstr(what, "Ed25519")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
255 bool ed25519pubkey = !strncasecmp(buf, "Ed25519PublicKey", 16) && strchr(" \t=", buf[16]) && strstr(what, "Ed25519");
261 if(block || ed25519pubkey)
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 Ed25519 keypair, and ask for a file to store
361 static bool ed25519_keygen(bool ask) {
364 char *pubname, *privname;
366 fprintf(stderr, "Generating Ed25519 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 "ed25519_key.priv", confbase);
375 f = ask_and_open(privname, "private Ed25519 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 "ed25519_key.pub", confbase);
395 f = ask_and_open(pubname, "public Ed25519 key", "a", ask, 0666);
401 char *pubkey = ecdsa_get_base64_public_key(key);
402 fprintf(f, "Ed25519PublicKey = %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 // Make sure the key size is a multiple of 8 bits.
423 // Force them to be between 1024 and 8192 bits long.
429 fprintf(stderr, "Generating %d bits keys:\n", bits);
431 if(!(key = rsa_generate(bits, 0x10001))) {
432 fprintf(stderr, "Error during key generation!\n");
435 fprintf(stderr, "Done.\n");
437 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
438 f = ask_and_open(privname, "private RSA key", "a", ask, 0600);
444 if(!rsa_write_pem_private_key(key, f)) {
445 fprintf(stderr, "Error writing private key!\n");
454 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
456 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
458 f = ask_and_open(pubname, "public RSA key", "a", ask, 0666);
464 if(!rsa_write_pem_public_key(key, f)) {
465 fprintf(stderr, "Error writing public key!\n");
480 bool recvline(int fd, char *line, size_t len) {
481 char *newline = NULL;
486 while(!(newline = memchr(buffer, '\n', blen))) {
487 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
488 if(result == -1 && sockerrno == EINTR)
495 if(newline - buffer >= len)
498 len = newline - buffer;
500 memcpy(line, buffer, len);
502 memmove(buffer, newline + 1, blen - len - 1);
508 bool recvdata(int fd, char *data, size_t len) {
513 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
514 if(result == -1 && sockerrno == EINTR)
521 memcpy(data, buffer, len);
522 memmove(buffer, buffer + len, blen - len);
528 bool sendline(int fd, char *format, ...) {
529 static char buffer[4096];
534 va_start(ap, format);
535 blen = vsnprintf(buffer, sizeof buffer, format, ap);
538 if(blen < 1 || blen >= sizeof buffer)
545 int result = send(fd, p, blen, MSG_NOSIGNAL);
546 if(result == -1 && sockerrno == EINTR)
557 static void pcap(int fd, FILE *out, int snaplen) {
558 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
566 uint32_t tz_accuracy;
573 snaplen ?: sizeof data,
586 fwrite(&header, sizeof header, 1, out);
590 while(recvline(fd, line, sizeof line)) {
592 int n = sscanf(line, "%d %d %d", &code, &req, &len);
593 gettimeofday(&tv, NULL);
594 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
596 if(!recvdata(fd, data, len))
598 packet.tv_sec = tv.tv_sec;
599 packet.tv_usec = tv.tv_usec;
601 packet.origlen = len;
602 fwrite(&packet, sizeof packet, 1, out);
603 fwrite(data, len, 1, out);
608 static void logcontrol(int fd, FILE *out, int level) {
609 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
613 while(recvline(fd, line, sizeof line)) {
615 int n = sscanf(line, "%d %d %d", &code, &req, &len);
616 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
618 if(!recvdata(fd, data, len))
620 fwrite(data, len, 1, out);
627 static bool remove_service(void) {
628 SC_HANDLE manager = NULL;
629 SC_HANDLE service = NULL;
630 SERVICE_STATUS status = {0};
632 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
634 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
638 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
641 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
645 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
646 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
648 fprintf(stderr, "%s service stopped\n", identname);
650 if(!DeleteService(service)) {
651 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
655 fprintf(stderr, "%s service removed\n", identname);
661 bool connect_tincd(bool verbose) {
666 struct timeval tv = {0, 0};
667 if(select(fd + 1, &r, NULL, NULL, &tv)) {
668 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
676 FILE *f = fopen(pidfilename, "r");
679 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
686 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
688 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
696 struct sockaddr_un sa;
697 sa.sun_family = AF_UNIX;
698 strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
700 fd = socket(AF_UNIX, SOCK_STREAM, 0);
703 fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
707 if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
709 fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
715 struct addrinfo hints = {
716 .ai_family = AF_UNSPEC,
717 .ai_socktype = SOCK_STREAM,
718 .ai_protocol = IPPROTO_TCP,
722 struct addrinfo *res = NULL;
724 if(getaddrinfo(host, port, &hints, &res) || !res) {
726 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, sockstrerror(sockerrno));
730 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
733 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
738 unsigned long arg = 0;
740 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
742 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
746 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
748 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
758 static const int one = 1;
759 setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, (void *)&one, sizeof one);
765 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
767 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
773 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
775 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
777 fprintf(stderr, "Could not fully establish control socket connection\n");
787 static int cmd_start(int argc, char *argv[]) {
788 if(connect_tincd(false)) {
790 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
792 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
797 char *slash = strrchr(program_name, '/');
800 if ((c = strrchr(program_name, '\\')) > slash)
805 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
810 char **nargv = xzalloc((optind + argc) * sizeof *nargv);
813 for(int i = 1; i < optind; i++)
814 nargv[nargc++] = orig_argv[i];
815 for(int i = 1; i < argc; i++)
816 nargv[nargc++] = argv[i];
820 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
825 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
831 exit(execvp(c, nargv));
835 int status = -1, result;
837 signal(SIGINT, SIG_IGN);
839 result = waitpid(pid, &status, 0);
841 signal(SIGINT, SIG_DFL);
844 if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
845 fprintf(stderr, "Error starting %s\n", c);
853 static int cmd_stop(int argc, char *argv[]) {
855 fprintf(stderr, "Too many arguments!\n");
860 if(!connect_tincd(true)) {
862 if(kill(pid, SIGTERM)) {
863 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
867 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
868 waitpid(pid, NULL, 0);
875 sendline(fd, "%d %d", CONTROL, REQ_STOP);
877 while(recvline(fd, line, sizeof line)) {
878 // Wait for tincd to close the connection...
881 if(!remove_service())
891 static int cmd_restart(int argc, char *argv[]) {
893 return cmd_start(argc, argv);
896 static int cmd_reload(int argc, char *argv[]) {
898 fprintf(stderr, "Too many arguments!\n");
902 if(!connect_tincd(true))
905 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
906 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
907 fprintf(stderr, "Could not reload configuration.\n");
915 static int cmd_dump(int argc, char *argv[]) {
916 bool only_reachable = false;
918 if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
919 if(strcasecmp(argv[2], "nodes")) {
920 fprintf(stderr, "`reachable' only supported for nodes.\n");
924 only_reachable = true;
930 fprintf(stderr, "Invalid number of arguments.\n");
935 if(!connect_tincd(true))
940 if(!strcasecmp(argv[1], "nodes"))
941 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
942 else if(!strcasecmp(argv[1], "edges"))
943 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
944 else if(!strcasecmp(argv[1], "subnets"))
945 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
946 else if(!strcasecmp(argv[1], "connections"))
947 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
948 else if(!strcasecmp(argv[1], "graph")) {
949 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
950 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
952 } else if(!strcasecmp(argv[1], "digraph")) {
953 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
954 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
957 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
964 else if(do_graph == 2)
965 printf("digraph {\n");
967 while(recvline(fd, line, sizeof line)) {
968 char node1[4096], node2[4096];
969 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
971 if(do_graph && req == REQ_DUMP_NODES)
988 char local_host[4096];
989 char local_port[4096];
992 int cipher, digest, maclength, compression, distance, socket, weight;
993 short int pmtu, minmtu, maxmtu;
994 unsigned int options, status_int;
995 node_status_t status;
996 long int last_state_change;
999 case REQ_DUMP_NODES: {
1000 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);
1002 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1006 memcpy(&status, &status_int, sizeof status);
1009 const char *color = "black";
1010 if(!strcmp(host, "MYSELF"))
1012 else if(!status.reachable)
1014 else if(strcmp(via, node))
1016 else if(!status.validkey)
1020 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1022 if(only_reachable && !status.reachable)
1024 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",
1025 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1029 case REQ_DUMP_EDGES: {
1030 int n = sscanf(line, "%*d %*d %s %s %s port %s %s port %s %x %d", from, to, host, port, local_host, local_port, &options, &weight);
1032 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1037 float w = 1 + 65536.0 / weight;
1038 if(do_graph == 1 && strcmp(node1, node2) > 0)
1039 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1040 else if(do_graph == 2)
1041 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1043 printf("%s to %s at %s port %s local %s port %s options %x weight %d\n", from, to, host, port, local_host, local_port, options, weight);
1047 case REQ_DUMP_SUBNETS: {
1048 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1050 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1053 printf("%s owner %s\n", strip_weight(subnet), node);
1056 case REQ_DUMP_CONNECTIONS: {
1057 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1059 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1062 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1066 fprintf(stderr, "Unable to parse dump from tincd.\n");
1071 fprintf(stderr, "Error receiving dump.\n");
1075 static int cmd_purge(int argc, char *argv[]) {
1077 fprintf(stderr, "Too many arguments!\n");
1081 if(!connect_tincd(true))
1084 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1085 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1086 fprintf(stderr, "Could not purge old information.\n");
1093 static int cmd_debug(int argc, char *argv[]) {
1095 fprintf(stderr, "Invalid number of arguments.\n");
1099 if(!connect_tincd(true))
1102 int debuglevel = atoi(argv[1]);
1105 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1106 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1107 fprintf(stderr, "Could not set debug level.\n");
1111 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1115 static int cmd_retry(int argc, char *argv[]) {
1117 fprintf(stderr, "Too many arguments!\n");
1121 if(!connect_tincd(true))
1124 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1125 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1126 fprintf(stderr, "Could not retry outgoing connections.\n");
1133 static int cmd_connect(int argc, char *argv[]) {
1135 fprintf(stderr, "Invalid number of arguments.\n");
1139 if(!check_id(argv[1])) {
1140 fprintf(stderr, "Invalid name for node.\n");
1144 if(!connect_tincd(true))
1147 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1148 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1149 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1156 static int cmd_disconnect(int argc, char *argv[]) {
1158 fprintf(stderr, "Invalid number of arguments.\n");
1162 if(!check_id(argv[1])) {
1163 fprintf(stderr, "Invalid name for node.\n");
1167 if(!connect_tincd(true))
1170 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1171 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1172 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1179 static int cmd_top(int argc, char *argv[]) {
1181 fprintf(stderr, "Too many arguments!\n");
1186 if(!connect_tincd(true))
1192 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1197 static int cmd_pcap(int argc, char *argv[]) {
1199 fprintf(stderr, "Too many arguments!\n");
1203 if(!connect_tincd(true))
1206 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1211 static void sigint_handler(int sig) {
1212 fprintf(stderr, "\n");
1213 shutdown(fd, SHUT_RDWR);
1217 static int cmd_log(int argc, char *argv[]) {
1219 fprintf(stderr, "Too many arguments!\n");
1223 if(!connect_tincd(true))
1227 signal(SIGINT, sigint_handler);
1230 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1233 signal(SIGINT, SIG_DFL);
1241 static int cmd_pid(int argc, char *argv[]) {
1243 fprintf(stderr, "Too many arguments!\n");
1247 if(!connect_tincd(true) && !pid)
1250 printf("%d\n", pid);
1254 int rstrip(char *value) {
1255 int len = strlen(value);
1256 while(len && strchr("\t\r\n ", value[len - 1]))
1261 char *get_my_name(bool verbose) {
1262 FILE *f = fopen(tinc_conf, "r");
1265 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1271 while(fgets(buf, sizeof buf, f)) {
1272 int len = strcspn(buf, "\t =");
1274 value += strspn(value, "\t ");
1277 value += strspn(value, "\t ");
1282 if(strcasecmp(buf, "Name"))
1286 return strdup(value);
1292 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1296 const var_t variables[] = {
1297 /* Server configuration */
1298 {"AddressFamily", VAR_SERVER},
1299 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1300 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1301 {"BindToInterface", VAR_SERVER},
1302 {"Broadcast", VAR_SERVER | VAR_SAFE},
1303 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1304 {"DecrementTTL", VAR_SERVER},
1305 {"Device", VAR_SERVER},
1306 {"DeviceType", VAR_SERVER},
1307 {"DirectOnly", VAR_SERVER},
1308 {"Ed25519PrivateKeyFile", VAR_SERVER},
1309 {"ExperimentalProtocol", VAR_SERVER},
1310 {"Forwarding", VAR_SERVER},
1311 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1312 {"Hostnames", VAR_SERVER},
1313 {"IffOneQueue", VAR_SERVER},
1314 {"Interface", VAR_SERVER},
1315 {"KeyExpire", VAR_SERVER},
1316 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1317 {"LocalDiscovery", VAR_SERVER},
1318 {"MACExpire", VAR_SERVER},
1319 {"MaxConnectionBurst", VAR_SERVER},
1320 {"MaxOutputBufferSize", VAR_SERVER},
1321 {"MaxTimeout", VAR_SERVER},
1322 {"Mode", VAR_SERVER | VAR_SAFE},
1323 {"Name", VAR_SERVER},
1324 {"PingInterval", VAR_SERVER},
1325 {"PingTimeout", VAR_SERVER},
1326 {"PriorityInheritance", VAR_SERVER},
1327 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1328 {"PrivateKeyFile", VAR_SERVER},
1329 {"ProcessPriority", VAR_SERVER},
1330 {"Proxy", VAR_SERVER},
1331 {"ReplayWindow", VAR_SERVER},
1332 {"ScriptsExtension", VAR_SERVER},
1333 {"ScriptsInterpreter", VAR_SERVER},
1334 {"StrictSubnets", VAR_SERVER},
1335 {"TunnelServer", VAR_SERVER},
1336 {"UDPRcvBuf", VAR_SERVER},
1337 {"UDPSndBuf", VAR_SERVER},
1338 {"VDEGroup", VAR_SERVER},
1339 {"VDEPort", VAR_SERVER},
1340 /* Host configuration */
1341 {"Address", VAR_HOST | VAR_MULTIPLE},
1342 {"Cipher", VAR_SERVER | VAR_HOST},
1343 {"ClampMSS", VAR_SERVER | VAR_HOST},
1344 {"Compression", VAR_SERVER | VAR_HOST},
1345 {"Digest", VAR_SERVER | VAR_HOST},
1346 {"Ed25519PublicKey", VAR_HOST},
1347 {"Ed25519PublicKeyFile", VAR_SERVER | VAR_HOST},
1348 {"IndirectData", VAR_SERVER | VAR_HOST},
1349 {"MACLength", VAR_SERVER | VAR_HOST},
1350 {"PMTU", VAR_SERVER | VAR_HOST},
1351 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1353 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1354 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1355 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1356 {"TCPOnly", VAR_SERVER | VAR_HOST},
1357 {"Weight", VAR_HOST | VAR_SAFE},
1361 static int cmd_config(int argc, char *argv[]) {
1363 fprintf(stderr, "Invalid number of arguments.\n");
1367 if(strcasecmp(argv[0], "config"))
1371 if(!strcasecmp(argv[1], "get")) {
1373 } else if(!strcasecmp(argv[1], "add")) {
1374 argv++, argc--, action = 1;
1375 } else if(!strcasecmp(argv[1], "del")) {
1376 argv++, argc--, action = -1;
1377 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1378 argv++, argc--, action = 0;
1382 fprintf(stderr, "Invalid number of arguments.\n");
1386 // Concatenate the rest of the command line
1387 strncpy(line, argv[1], sizeof line - 1);
1388 for(int i = 2; i < argc; i++) {
1389 strncat(line, " ", sizeof line - 1 - strlen(line));
1390 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1393 // Liberal parsing into node name, variable name and value.
1399 len = strcspn(line, "\t =");
1401 value += strspn(value, "\t ");
1404 value += strspn(value, "\t ");
1407 variable = strchr(line, '.');
1416 fprintf(stderr, "No variable given.\n");
1420 if(action >= 0 && !*value) {
1421 fprintf(stderr, "No value for variable given.\n");
1425 if(action < -1 && *value)
1428 /* Some simple checks. */
1430 bool warnonremove = false;
1432 for(int i = 0; variables[i].name; i++) {
1433 if(strcasecmp(variables[i].name, variable))
1437 variable = (char *)variables[i].name;
1439 /* Discourage use of obsolete variables. */
1441 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1443 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1445 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1450 /* Don't put server variables in host config files */
1452 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1454 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1456 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1461 /* Should this go into our own host config file? */
1463 if(!node && !(variables[i].type & VAR_SERVER)) {
1464 node = get_my_name(true);
1469 /* Change "add" into "set" for variables that do not allow multiple occurences.
1470 Turn on warnings when it seems variables might be removed unintentionally. */
1472 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1473 warnonremove = true;
1475 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1476 warnonremove = true;
1482 if(node && !check_id(node)) {
1483 fprintf(stderr, "Invalid name for node.\n");
1488 if(force || action < 0) {
1489 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1491 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1496 // Open the right configuration file.
1499 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1501 filename = tinc_conf;
1503 FILE *f = fopen(filename, "r");
1505 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1509 char *tmpfile = NULL;
1513 xasprintf(&tmpfile, "%s.config.tmp", filename);
1514 tf = fopen(tmpfile, "w");
1516 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1522 // Copy the file, making modifications on the fly, unless we are just getting a value.
1526 bool removed = false;
1529 while(fgets(buf1, sizeof buf1, f)) {
1530 buf1[sizeof buf1 - 1] = 0;
1531 strncpy(buf2, buf1, sizeof buf2);
1533 // Parse line in a simple way
1537 len = strcspn(buf2, "\t =");
1538 bvalue = buf2 + len;
1539 bvalue += strspn(bvalue, "\t ");
1540 if(*bvalue == '=') {
1542 bvalue += strspn(bvalue, "\t ");
1548 if(!strcasecmp(buf2, variable)) {
1552 printf("%s\n", bvalue);
1554 } else if(action == -1) {
1555 if(!*value || !strcasecmp(bvalue, value)) {
1560 } else if(action == 0) {
1561 // Warn if "set" was used for variables that can occur multiple times
1562 if(warnonremove && strcasecmp(bvalue, value))
1563 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1565 // Already set? Delete the rest...
1569 // Otherwise, replace.
1570 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1571 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1580 // Copy original line...
1581 if(fputs(buf1, tf) < 0) {
1582 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1586 // Add newline if it is missing...
1587 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1588 if(fputc('\n', tf) < 0) {
1589 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1596 // Make sure we read everything...
1597 if(ferror(f) || !feof(f)) {
1598 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1603 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1607 // Add new variable if necessary.
1608 if(action > 0 || (action == 0 && !set)) {
1609 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1610 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1617 fprintf(stderr, "No matching configuration variables found.\n");
1621 // Make sure we wrote everything...
1623 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1627 // Could we find what we had to remove?
1628 if(action < 0 && !removed) {
1630 fprintf(stderr, "No configuration variables deleted.\n");
1634 // Replace the configuration file with the new one
1636 if(remove(filename)) {
1637 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1641 if(rename(tmpfile, filename)) {
1642 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1646 // Silently try notifying a running tincd of changes.
1647 if(connect_tincd(false))
1648 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1653 bool check_id(const char *name) {
1657 for(int i = 0; i < strlen(name); i++) {
1658 if(!isalnum(name[i]) && name[i] != '_')
1665 static bool try_bind(int port) {
1666 struct addrinfo *ai = NULL;
1667 struct addrinfo hint = {
1668 .ai_flags = AI_PASSIVE,
1669 .ai_family = AF_UNSPEC,
1670 .ai_socktype = SOCK_STREAM,
1671 .ai_protocol = IPPROTO_TCP,
1675 snprintf(portstr, sizeof portstr, "%d", port);
1677 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1681 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1684 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1694 int check_port(char *name) {
1698 fprintf(stderr, "Warning: could not bind to port 655. ");
1700 for(int i = 0; i < 100; i++) {
1701 int port = 0x1000 + (rand() & 0x7fff);
1702 if(try_bind(port)) {
1704 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1705 FILE *f = fopen(filename, "a");
1708 fprintf(stderr, "Please change tinc's Port manually.\n");
1712 fprintf(f, "Port = %d\n", port);
1714 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1719 fprintf(stderr, "Please change tinc's Port manually.\n");
1723 static int cmd_init(int argc, char *argv[]) {
1724 if(!access(tinc_conf, F_OK)) {
1725 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1730 fprintf(stderr, "Too many arguments!\n");
1732 } else if(argc < 2) {
1735 fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1736 if(!fgets(buf, sizeof buf, stdin)) {
1737 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1740 int len = rstrip(buf);
1742 fprintf(stderr, "No name given!\n");
1747 fprintf(stderr, "No Name given!\n");
1751 name = strdup(argv[1]);
1753 fprintf(stderr, "No Name given!\n");
1758 if(!check_id(name)) {
1759 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1763 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1764 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1768 if(mkdir(confbase, 0777) && errno != EEXIST) {
1769 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1773 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1774 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1778 FILE *f = fopen(tinc_conf, "w");
1780 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1784 fprintf(f, "Name = %s\n", name);
1787 if(!rsa_keygen(2048, false) || !ed25519_keygen(false))
1794 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1795 if(access(filename, F_OK)) {
1796 FILE *f = fopenmask(filename, "w", 0777);
1798 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1801 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");
1810 static int cmd_generate_keys(int argc, char *argv[]) {
1812 fprintf(stderr, "Too many arguments!\n");
1817 name = get_my_name(false);
1819 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ed25519_keygen(true));
1822 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1824 fprintf(stderr, "Too many arguments!\n");
1829 name = get_my_name(false);
1831 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1834 static int cmd_generate_ed25519_keys(int argc, char *argv[]) {
1836 fprintf(stderr, "Too many arguments!\n");
1841 name = get_my_name(false);
1843 return !ed25519_keygen(true);
1846 static int cmd_help(int argc, char *argv[]) {
1851 static int cmd_version(int argc, char *argv[]) {
1853 fprintf(stderr, "Too many arguments!\n");
1861 static int cmd_info(int argc, char *argv[]) {
1863 fprintf(stderr, "Invalid number of arguments.\n");
1867 if(!connect_tincd(true))
1870 return info(fd, argv[1]);
1873 static const char *conffiles[] = {
1884 static int cmd_edit(int argc, char *argv[]) {
1886 fprintf(stderr, "Invalid number of arguments.\n");
1890 char *filename = NULL;
1892 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1893 for(int i = 0; conffiles[i]; i++) {
1894 if(!strcmp(argv[1], conffiles[i])) {
1895 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1904 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1905 char *dash = strchr(argv[1], '-');
1908 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1909 fprintf(stderr, "Invalid configuration filename.\n");
1917 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1919 xasprintf(&command, "edit \"%s\"", filename);
1921 int result = system(command);
1925 // Silently try notifying a running tincd of changes.
1926 if(connect_tincd(false))
1927 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1932 static int export(const char *name, FILE *out) {
1934 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1935 FILE *in = fopen(filename, "r");
1937 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1941 fprintf(out, "Name = %s\n", name);
1943 while(fgets(buf, sizeof buf, in)) {
1944 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1949 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1958 static int cmd_export(int argc, char *argv[]) {
1960 fprintf(stderr, "Too many arguments!\n");
1964 char *name = get_my_name(true);
1968 int result = export(name, stdout);
1976 static int cmd_export_all(int argc, char *argv[]) {
1978 fprintf(stderr, "Too many arguments!\n");
1982 DIR *dir = opendir(hosts_dir);
1984 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1992 while((ent = readdir(dir))) {
1993 if(!check_id(ent->d_name))
1999 printf("#---------------------------------------------------------------#\n");
2001 result |= export(ent->d_name, stdout);
2010 static int cmd_import(int argc, char *argv[]) {
2012 fprintf(stderr, "Too many arguments!\n");
2021 char *filename = NULL;
2023 bool firstline = true;
2025 while(fgets(buf, sizeof buf, in)) {
2026 if(sscanf(buf, "Name = %s", name) == 1) {
2029 if(!check_id(name)) {
2030 fprintf(stderr, "Invalid Name in input!\n");
2038 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2040 if(!force && !access(filename, F_OK)) {
2041 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2046 out = fopen(filename, "w");
2048 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2054 } else if(firstline) {
2055 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2060 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2064 if(fputs(buf, out) < 0) {
2065 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2075 fprintf(stderr, "Imported %d host configuration files.\n", count);
2078 fprintf(stderr, "No host configuration files imported.\n");
2083 static int cmd_exchange(int argc, char *argv[]) {
2084 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2087 static int cmd_exchange_all(int argc, char *argv[]) {
2088 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2091 static int switch_network(char *name) {
2103 free(unixsocketname);
2104 unixsocketname = NULL;
2110 netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2113 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2114 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2115 xasprintf(&prompt, "%s> ", identname);
2120 static int cmd_network(int argc, char *argv[]) {
2122 fprintf(stderr, "Too many arguments!\n");
2127 return switch_network(argv[1]);
2129 DIR *dir = opendir(confdir);
2131 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2136 while((ent = readdir(dir))) {
2137 if(*ent->d_name == '.')
2140 if(!strcmp(ent->d_name, "tinc.conf")) {
2146 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2147 if(!access(fname, R_OK))
2148 printf("%s\n", ent->d_name);
2157 static const struct {
2158 const char *command;
2159 int (*function)(int argc, char *argv[]);
2162 {"start", cmd_start},
2164 {"restart", cmd_restart},
2165 {"reload", cmd_reload},
2167 {"purge", cmd_purge},
2168 {"debug", cmd_debug},
2169 {"retry", cmd_retry},
2170 {"connect", cmd_connect},
2171 {"disconnect", cmd_disconnect},
2176 {"config", cmd_config, true},
2177 {"add", cmd_config},
2178 {"del", cmd_config},
2179 {"get", cmd_config},
2180 {"set", cmd_config},
2182 {"generate-keys", cmd_generate_keys},
2183 {"generate-rsa-keys", cmd_generate_rsa_keys},
2184 {"generate-ed25519-keys", cmd_generate_ed25519_keys},
2186 {"version", cmd_version},
2189 {"export", cmd_export},
2190 {"export-all", cmd_export_all},
2191 {"import", cmd_import},
2192 {"exchange", cmd_exchange},
2193 {"exchange-all", cmd_exchange_all},
2194 {"invite", cmd_invite},
2196 {"network", cmd_network},
2200 #ifdef HAVE_READLINE
2201 static char *complete_command(const char *text, int state) {
2209 while(commands[i].command) {
2210 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2211 return xstrdup(commands[i].command);
2218 static char *complete_dump(const char *text, int state) {
2219 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2228 if(!strncasecmp(matches[i], text, strlen(text)))
2229 return xstrdup(matches[i]);
2236 static char *complete_config(const char *text, int state) {
2244 while(variables[i].name) {
2245 char *dot = strchr(text, '.');
2247 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2249 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2253 if(!strncasecmp(variables[i].name, text, strlen(text)))
2254 return xstrdup(variables[i].name);
2262 static char *complete_info(const char *text, int state) {
2266 if(!connect_tincd(false))
2268 // Check the list of nodes
2269 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2270 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2273 while(recvline(fd, line, sizeof line)) {
2275 int n = sscanf(line, "%d %d %s", &code, &req, item);
2285 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2289 if(!strncmp(item, text, strlen(text)))
2290 return xstrdup(strip_weight(item));
2296 static char *complete_nothing(const char *text, int state) {
2300 static char **completion (const char *text, int start, int end) {
2301 char **matches = NULL;
2304 matches = rl_completion_matches(text, complete_command);
2305 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2306 matches = rl_completion_matches(text, complete_dump);
2307 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2308 matches = rl_completion_matches(text, complete_config);
2309 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2310 matches = rl_completion_matches(text, complete_config);
2311 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2312 matches = rl_completion_matches(text, complete_config);
2313 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2314 matches = rl_completion_matches(text, complete_config);
2315 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2316 matches = rl_completion_matches(text, complete_info);
2322 static int cmd_shell(int argc, char *argv[]) {
2323 xasprintf(&prompt, "%s> ", identname);
2327 int maxargs = argc + 16;
2328 char **nargv = xmalloc(maxargs * sizeof *nargv);
2330 for(int i = 0; i < argc; i++)
2333 #ifdef HAVE_READLINE
2334 rl_readline_name = "tinc";
2335 rl_completion_entry_function = complete_nothing;
2336 rl_attempted_completion_function = completion;
2337 rl_filename_completion_desired = 0;
2342 #ifdef HAVE_READLINE
2346 rl_basic_word_break_characters = "\t\n ";
2347 line = readline(prompt);
2349 copy = xstrdup(line);
2351 line = fgets(buf, sizeof buf, stdin);
2355 fputs(prompt, stdout);
2357 line = fgets(buf, sizeof buf, stdin);
2363 /* Ignore comments */
2371 char *p = line + strspn(line, " \t\n");
2372 char *next = strtok(p, " \t\n");
2375 if(nargc >= maxargs) {
2376 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2379 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2384 next = strtok(NULL, " \t\n");
2390 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2395 for(int i = 0; commands[i].command; i++) {
2396 if(!strcasecmp(nargv[argc], commands[i].command)) {
2397 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2403 #ifdef HAVE_READLINE
2409 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2422 int main(int argc, char *argv[]) {
2423 program_name = argv[0];
2427 if(!parse_options(argc, argv))
2431 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2432 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2445 static struct WSAData wsa_state;
2447 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2448 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2456 tty = isatty(0) && isatty(1);
2459 return cmd_shell(argc, argv);
2461 for(int i = 0; commands[i].command; i++) {
2462 if(!strcasecmp(argv[optind], commands[i].command))
2463 return commands[i].function(argc - optind, argv + optind);
2466 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);