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, " 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 && errno == 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 && errno == 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 && errno == 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, strerror(errno));
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)
990 int cipher, digest, maclength, compression, distance, socket, weight;
991 short int pmtu, minmtu, maxmtu;
992 unsigned int options, status_int;
993 node_status_t status;
994 long int last_state_change;
997 case REQ_DUMP_NODES: {
998 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);
1000 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1004 memcpy(&status, &status_int, sizeof status);
1007 const char *color = "black";
1008 if(!strcmp(host, "MYSELF"))
1010 else if(!status.reachable)
1012 else if(strcmp(via, node))
1014 else if(!status.validkey)
1018 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1020 if(only_reachable && !status.reachable)
1022 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",
1023 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1027 case REQ_DUMP_EDGES: {
1028 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1030 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1035 float w = 1 + 65536.0 / weight;
1036 if(do_graph == 1 && strcmp(node1, node2) > 0)
1037 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1038 else if(do_graph == 2)
1039 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1041 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1045 case REQ_DUMP_SUBNETS: {
1046 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1048 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1051 printf("%s owner %s\n", strip_weight(subnet), node);
1054 case REQ_DUMP_CONNECTIONS: {
1055 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1057 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1060 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1064 fprintf(stderr, "Unable to parse dump from tincd.\n");
1069 fprintf(stderr, "Error receiving dump.\n");
1073 static int cmd_purge(int argc, char *argv[]) {
1075 fprintf(stderr, "Too many arguments!\n");
1079 if(!connect_tincd(true))
1082 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1083 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1084 fprintf(stderr, "Could not purge old information.\n");
1091 static int cmd_debug(int argc, char *argv[]) {
1093 fprintf(stderr, "Invalid number of arguments.\n");
1097 if(!connect_tincd(true))
1100 int debuglevel = atoi(argv[1]);
1103 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1104 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1105 fprintf(stderr, "Could not set debug level.\n");
1109 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1113 static int cmd_retry(int argc, char *argv[]) {
1115 fprintf(stderr, "Too many arguments!\n");
1119 if(!connect_tincd(true))
1122 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1123 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1124 fprintf(stderr, "Could not retry outgoing connections.\n");
1131 static int cmd_connect(int argc, char *argv[]) {
1133 fprintf(stderr, "Invalid number of arguments.\n");
1137 if(!check_id(argv[1])) {
1138 fprintf(stderr, "Invalid name for node.\n");
1142 if(!connect_tincd(true))
1145 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1146 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1147 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1154 static int cmd_disconnect(int argc, char *argv[]) {
1156 fprintf(stderr, "Invalid number of arguments.\n");
1160 if(!check_id(argv[1])) {
1161 fprintf(stderr, "Invalid name for node.\n");
1165 if(!connect_tincd(true))
1168 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1169 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1170 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1177 static int cmd_top(int argc, char *argv[]) {
1179 fprintf(stderr, "Too many arguments!\n");
1184 if(!connect_tincd(true))
1190 fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1195 static int cmd_pcap(int argc, char *argv[]) {
1197 fprintf(stderr, "Too many arguments!\n");
1201 if(!connect_tincd(true))
1204 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1209 static void sigint_handler(int sig) {
1210 fprintf(stderr, "\n");
1211 shutdown(fd, SHUT_RDWR);
1215 static int cmd_log(int argc, char *argv[]) {
1217 fprintf(stderr, "Too many arguments!\n");
1221 if(!connect_tincd(true))
1225 signal(SIGINT, sigint_handler);
1228 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1231 signal(SIGINT, SIG_DFL);
1239 static int cmd_pid(int argc, char *argv[]) {
1241 fprintf(stderr, "Too many arguments!\n");
1245 if(!connect_tincd(true) && !pid)
1248 printf("%d\n", pid);
1252 int rstrip(char *value) {
1253 int len = strlen(value);
1254 while(len && strchr("\t\r\n ", value[len - 1]))
1259 char *get_my_name(bool verbose) {
1260 FILE *f = fopen(tinc_conf, "r");
1263 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1269 while(fgets(buf, sizeof buf, f)) {
1270 int len = strcspn(buf, "\t =");
1272 value += strspn(value, "\t ");
1275 value += strspn(value, "\t ");
1280 if(strcasecmp(buf, "Name"))
1284 return strdup(value);
1290 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1294 const var_t variables[] = {
1295 /* Server configuration */
1296 {"AddressFamily", VAR_SERVER},
1297 {"AutoConnect", VAR_SERVER | VAR_SAFE},
1298 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1299 {"BindToInterface", VAR_SERVER},
1300 {"Broadcast", VAR_SERVER | VAR_SAFE},
1301 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1302 {"DecrementTTL", VAR_SERVER},
1303 {"Device", VAR_SERVER},
1304 {"DeviceType", VAR_SERVER},
1305 {"DirectOnly", VAR_SERVER},
1306 {"Ed25519PrivateKeyFile", VAR_SERVER},
1307 {"ExperimentalProtocol", VAR_SERVER},
1308 {"Forwarding", VAR_SERVER},
1309 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1310 {"Hostnames", VAR_SERVER},
1311 {"IffOneQueue", VAR_SERVER},
1312 {"Interface", VAR_SERVER},
1313 {"KeyExpire", VAR_SERVER},
1314 {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1315 {"LocalDiscovery", VAR_SERVER},
1316 {"MACExpire", VAR_SERVER},
1317 {"MaxConnectionBurst", VAR_SERVER},
1318 {"MaxOutputBufferSize", VAR_SERVER},
1319 {"MaxTimeout", VAR_SERVER},
1320 {"Mode", VAR_SERVER | VAR_SAFE},
1321 {"Name", VAR_SERVER},
1322 {"PingInterval", VAR_SERVER},
1323 {"PingTimeout", VAR_SERVER},
1324 {"PriorityInheritance", VAR_SERVER},
1325 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1326 {"PrivateKeyFile", VAR_SERVER},
1327 {"ProcessPriority", VAR_SERVER},
1328 {"Proxy", VAR_SERVER},
1329 {"ReplayWindow", VAR_SERVER},
1330 {"ScriptsExtension", VAR_SERVER},
1331 {"ScriptsInterpreter", VAR_SERVER},
1332 {"StrictSubnets", VAR_SERVER},
1333 {"TunnelServer", VAR_SERVER},
1334 {"UDPRcvBuf", VAR_SERVER},
1335 {"UDPSndBuf", VAR_SERVER},
1336 {"VDEGroup", VAR_SERVER},
1337 {"VDEPort", VAR_SERVER},
1338 /* Host configuration */
1339 {"Address", VAR_HOST | VAR_MULTIPLE},
1340 {"Cipher", VAR_SERVER | VAR_HOST},
1341 {"ClampMSS", VAR_SERVER | VAR_HOST},
1342 {"Compression", VAR_SERVER | VAR_HOST},
1343 {"Digest", VAR_SERVER | VAR_HOST},
1344 {"Ed25519PublicKey", VAR_HOST},
1345 {"Ed25519PublicKeyFile", VAR_SERVER | VAR_HOST},
1346 {"IndirectData", VAR_SERVER | VAR_HOST},
1347 {"MACLength", VAR_SERVER | VAR_HOST},
1348 {"PMTU", VAR_SERVER | VAR_HOST},
1349 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1351 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1352 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1353 {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1354 {"TCPOnly", VAR_SERVER | VAR_HOST},
1355 {"Weight", VAR_HOST | VAR_SAFE},
1359 static int cmd_config(int argc, char *argv[]) {
1361 fprintf(stderr, "Invalid number of arguments.\n");
1365 if(strcasecmp(argv[0], "config"))
1369 if(!strcasecmp(argv[1], "get")) {
1371 } else if(!strcasecmp(argv[1], "add")) {
1372 argv++, argc--, action = 1;
1373 } else if(!strcasecmp(argv[1], "del")) {
1374 argv++, argc--, action = -1;
1375 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1376 argv++, argc--, action = 0;
1380 fprintf(stderr, "Invalid number of arguments.\n");
1384 // Concatenate the rest of the command line
1385 strncpy(line, argv[1], sizeof line - 1);
1386 for(int i = 2; i < argc; i++) {
1387 strncat(line, " ", sizeof line - 1 - strlen(line));
1388 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1391 // Liberal parsing into node name, variable name and value.
1397 len = strcspn(line, "\t =");
1399 value += strspn(value, "\t ");
1402 value += strspn(value, "\t ");
1405 variable = strchr(line, '.');
1414 fprintf(stderr, "No variable given.\n");
1418 if(action >= 0 && !*value) {
1419 fprintf(stderr, "No value for variable given.\n");
1423 if(action < -1 && *value)
1426 /* Some simple checks. */
1428 bool warnonremove = false;
1430 for(int i = 0; variables[i].name; i++) {
1431 if(strcasecmp(variables[i].name, variable))
1435 variable = (char *)variables[i].name;
1437 /* Discourage use of obsolete variables. */
1439 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1441 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1443 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1448 /* Don't put server variables in host config files */
1450 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1452 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1454 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1459 /* Should this go into our own host config file? */
1461 if(!node && !(variables[i].type & VAR_SERVER)) {
1462 node = get_my_name(true);
1467 /* Change "add" into "set" for variables that do not allow multiple occurences.
1468 Turn on warnings when it seems variables might be removed unintentionally. */
1470 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1471 warnonremove = true;
1473 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1474 warnonremove = true;
1480 if(node && !check_id(node)) {
1481 fprintf(stderr, "Invalid name for node.\n");
1486 if(force || action < 0) {
1487 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1489 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1494 // Open the right configuration file.
1497 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1499 filename = tinc_conf;
1501 FILE *f = fopen(filename, "r");
1503 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1507 char *tmpfile = NULL;
1511 xasprintf(&tmpfile, "%s.config.tmp", filename);
1512 tf = fopen(tmpfile, "w");
1514 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1520 // Copy the file, making modifications on the fly, unless we are just getting a value.
1524 bool removed = false;
1527 while(fgets(buf1, sizeof buf1, f)) {
1528 buf1[sizeof buf1 - 1] = 0;
1529 strncpy(buf2, buf1, sizeof buf2);
1531 // Parse line in a simple way
1535 len = strcspn(buf2, "\t =");
1536 bvalue = buf2 + len;
1537 bvalue += strspn(bvalue, "\t ");
1538 if(*bvalue == '=') {
1540 bvalue += strspn(bvalue, "\t ");
1546 if(!strcasecmp(buf2, variable)) {
1550 printf("%s\n", bvalue);
1552 } else if(action == -1) {
1553 if(!*value || !strcasecmp(bvalue, value)) {
1558 } else if(action == 0) {
1559 // Warn if "set" was used for variables that can occur multiple times
1560 if(warnonremove && strcasecmp(bvalue, value))
1561 fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1563 // Already set? Delete the rest...
1567 // Otherwise, replace.
1568 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1569 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1578 // Copy original line...
1579 if(fputs(buf1, tf) < 0) {
1580 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1584 // Add newline if it is missing...
1585 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1586 if(fputc('\n', tf) < 0) {
1587 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1594 // Make sure we read everything...
1595 if(ferror(f) || !feof(f)) {
1596 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1601 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1605 // Add new variable if necessary.
1606 if(action > 0 || (action == 0 && !set)) {
1607 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1608 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1615 fprintf(stderr, "No matching configuration variables found.\n");
1619 // Make sure we wrote everything...
1621 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1625 // Could we find what we had to remove?
1626 if(action < 0 && !removed) {
1628 fprintf(stderr, "No configuration variables deleted.\n");
1632 // Replace the configuration file with the new one
1634 if(remove(filename)) {
1635 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1639 if(rename(tmpfile, filename)) {
1640 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1644 // Silently try notifying a running tincd of changes.
1645 if(connect_tincd(false))
1646 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1651 bool check_id(const char *name) {
1655 for(int i = 0; i < strlen(name); i++) {
1656 if(!isalnum(name[i]) && name[i] != '_')
1663 static bool try_bind(int port) {
1664 struct addrinfo *ai = NULL;
1665 struct addrinfo hint = {
1666 .ai_flags = AI_PASSIVE,
1667 .ai_family = AF_UNSPEC,
1668 .ai_socktype = SOCK_STREAM,
1669 .ai_protocol = IPPROTO_TCP,
1673 snprintf(portstr, sizeof portstr, "%d", port);
1675 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1679 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1682 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1692 int check_port(char *name) {
1696 fprintf(stderr, "Warning: could not bind to port 655. ");
1698 for(int i = 0; i < 100; i++) {
1699 int port = 0x1000 + (rand() & 0x7fff);
1700 if(try_bind(port)) {
1702 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1703 FILE *f = fopen(filename, "a");
1706 fprintf(stderr, "Please change tinc's Port manually.\n");
1710 fprintf(f, "Port = %d\n", port);
1712 fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1717 fprintf(stderr, "Please change tinc's Port manually.\n");
1721 static int cmd_init(int argc, char *argv[]) {
1722 if(!access(tinc_conf, F_OK)) {
1723 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1728 fprintf(stderr, "Too many arguments!\n");
1730 } else if(argc < 2) {
1733 fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1734 if(!fgets(buf, sizeof buf, stdin)) {
1735 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1738 int len = rstrip(buf);
1740 fprintf(stderr, "No name given!\n");
1745 fprintf(stderr, "No Name given!\n");
1749 name = strdup(argv[1]);
1751 fprintf(stderr, "No Name given!\n");
1756 if(!check_id(name)) {
1757 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1761 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1762 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1766 if(mkdir(confbase, 0777) && errno != EEXIST) {
1767 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1771 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1772 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1776 FILE *f = fopen(tinc_conf, "w");
1778 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1782 fprintf(f, "Name = %s\n", name);
1785 if(!rsa_keygen(2048, false) || !ed25519_keygen(false))
1792 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1793 if(access(filename, F_OK)) {
1794 FILE *f = fopenmask(filename, "w", 0777);
1796 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1799 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");
1808 static int cmd_generate_keys(int argc, char *argv[]) {
1810 fprintf(stderr, "Too many arguments!\n");
1815 name = get_my_name(false);
1817 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ed25519_keygen(true));
1820 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1822 fprintf(stderr, "Too many arguments!\n");
1827 name = get_my_name(false);
1829 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1832 static int cmd_generate_ed25519_keys(int argc, char *argv[]) {
1834 fprintf(stderr, "Too many arguments!\n");
1839 name = get_my_name(false);
1841 return !ed25519_keygen(true);
1844 static int cmd_help(int argc, char *argv[]) {
1849 static int cmd_version(int argc, char *argv[]) {
1851 fprintf(stderr, "Too many arguments!\n");
1859 static int cmd_info(int argc, char *argv[]) {
1861 fprintf(stderr, "Invalid number of arguments.\n");
1865 if(!connect_tincd(true))
1868 return info(fd, argv[1]);
1871 static const char *conffiles[] = {
1882 static int cmd_edit(int argc, char *argv[]) {
1884 fprintf(stderr, "Invalid number of arguments.\n");
1888 char *filename = NULL;
1890 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1891 for(int i = 0; conffiles[i]; i++) {
1892 if(!strcmp(argv[1], conffiles[i])) {
1893 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1902 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1903 char *dash = strchr(argv[1], '-');
1906 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1907 fprintf(stderr, "Invalid configuration filename.\n");
1915 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1917 xasprintf(&command, "edit \"%s\"", filename);
1919 int result = system(command);
1923 // Silently try notifying a running tincd of changes.
1924 if(connect_tincd(false))
1925 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1930 static int export(const char *name, FILE *out) {
1932 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1933 FILE *in = fopen(filename, "r");
1935 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1939 fprintf(out, "Name = %s\n", name);
1941 while(fgets(buf, sizeof buf, in)) {
1942 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1947 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1956 static int cmd_export(int argc, char *argv[]) {
1958 fprintf(stderr, "Too many arguments!\n");
1962 char *name = get_my_name(true);
1966 int result = export(name, stdout);
1974 static int cmd_export_all(int argc, char *argv[]) {
1976 fprintf(stderr, "Too many arguments!\n");
1980 DIR *dir = opendir(hosts_dir);
1982 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1990 while((ent = readdir(dir))) {
1991 if(!check_id(ent->d_name))
1997 printf("#---------------------------------------------------------------#\n");
1999 result |= export(ent->d_name, stdout);
2008 static int cmd_import(int argc, char *argv[]) {
2010 fprintf(stderr, "Too many arguments!\n");
2019 char *filename = NULL;
2021 bool firstline = true;
2023 while(fgets(buf, sizeof buf, in)) {
2024 if(sscanf(buf, "Name = %s", name) == 1) {
2027 if(!check_id(name)) {
2028 fprintf(stderr, "Invalid Name in input!\n");
2036 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2038 if(!force && !access(filename, F_OK)) {
2039 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2044 out = fopen(filename, "w");
2046 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2052 } else if(firstline) {
2053 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2058 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2062 if(fputs(buf, out) < 0) {
2063 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2073 fprintf(stderr, "Imported %d host configuration files.\n", count);
2076 fprintf(stderr, "No host configuration files imported.\n");
2081 static int cmd_exchange(int argc, char *argv[]) {
2082 return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2085 static int cmd_exchange_all(int argc, char *argv[]) {
2086 return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2089 static int switch_network(char *name) {
2101 free(unixsocketname);
2102 unixsocketname = NULL;
2108 netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2111 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2112 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2113 xasprintf(&prompt, "%s> ", identname);
2118 static int cmd_network(int argc, char *argv[]) {
2120 fprintf(stderr, "Too many arguments!\n");
2125 return switch_network(argv[1]);
2127 DIR *dir = opendir(confdir);
2129 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2134 while((ent = readdir(dir))) {
2135 if(*ent->d_name == '.')
2138 if(!strcmp(ent->d_name, "tinc.conf")) {
2144 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2145 if(!access(fname, R_OK))
2146 printf("%s\n", ent->d_name);
2155 static const struct {
2156 const char *command;
2157 int (*function)(int argc, char *argv[]);
2160 {"start", cmd_start},
2162 {"restart", cmd_restart},
2163 {"reload", cmd_reload},
2165 {"purge", cmd_purge},
2166 {"debug", cmd_debug},
2167 {"retry", cmd_retry},
2168 {"connect", cmd_connect},
2169 {"disconnect", cmd_disconnect},
2174 {"config", cmd_config, true},
2175 {"add", cmd_config},
2176 {"del", cmd_config},
2177 {"get", cmd_config},
2178 {"set", cmd_config},
2180 {"generate-keys", cmd_generate_keys},
2181 {"generate-rsa-keys", cmd_generate_rsa_keys},
2182 {"generate-ed25519-keys", cmd_generate_ed25519_keys},
2184 {"version", cmd_version},
2187 {"export", cmd_export},
2188 {"export-all", cmd_export_all},
2189 {"import", cmd_import},
2190 {"exchange", cmd_exchange},
2191 {"exchange-all", cmd_exchange_all},
2192 {"invite", cmd_invite},
2194 {"network", cmd_network},
2198 #ifdef HAVE_READLINE
2199 static char *complete_command(const char *text, int state) {
2207 while(commands[i].command) {
2208 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2209 return xstrdup(commands[i].command);
2216 static char *complete_dump(const char *text, int state) {
2217 const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2226 if(!strncasecmp(matches[i], text, strlen(text)))
2227 return xstrdup(matches[i]);
2234 static char *complete_config(const char *text, int state) {
2242 while(variables[i].name) {
2243 char *dot = strchr(text, '.');
2245 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2247 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2251 if(!strncasecmp(variables[i].name, text, strlen(text)))
2252 return xstrdup(variables[i].name);
2260 static char *complete_info(const char *text, int state) {
2264 if(!connect_tincd(false))
2266 // Check the list of nodes
2267 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2268 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2271 while(recvline(fd, line, sizeof line)) {
2273 int n = sscanf(line, "%d %d %s", &code, &req, item);
2283 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2287 if(!strncmp(item, text, strlen(text)))
2288 return xstrdup(strip_weight(item));
2294 static char *complete_nothing(const char *text, int state) {
2298 static char **completion (const char *text, int start, int end) {
2299 char **matches = NULL;
2302 matches = rl_completion_matches(text, complete_command);
2303 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2304 matches = rl_completion_matches(text, complete_dump);
2305 else if(!strncasecmp(rl_line_buffer, "add ", 4))
2306 matches = rl_completion_matches(text, complete_config);
2307 else if(!strncasecmp(rl_line_buffer, "del ", 4))
2308 matches = rl_completion_matches(text, complete_config);
2309 else if(!strncasecmp(rl_line_buffer, "get ", 4))
2310 matches = rl_completion_matches(text, complete_config);
2311 else if(!strncasecmp(rl_line_buffer, "set ", 4))
2312 matches = rl_completion_matches(text, complete_config);
2313 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2314 matches = rl_completion_matches(text, complete_info);
2320 static int cmd_shell(int argc, char *argv[]) {
2321 xasprintf(&prompt, "%s> ", identname);
2325 int maxargs = argc + 16;
2326 char **nargv = xmalloc(maxargs * sizeof *nargv);
2328 for(int i = 0; i < argc; i++)
2331 #ifdef HAVE_READLINE
2332 rl_readline_name = "tinc";
2333 rl_completion_entry_function = complete_nothing;
2334 rl_attempted_completion_function = completion;
2335 rl_filename_completion_desired = 0;
2340 #ifdef HAVE_READLINE
2344 rl_basic_word_break_characters = "\t\n ";
2345 line = readline(prompt);
2347 copy = xstrdup(line);
2349 line = fgets(buf, sizeof buf, stdin);
2353 fputs(prompt, stdout);
2355 line = fgets(buf, sizeof buf, stdin);
2361 /* Ignore comments */
2369 char *p = line + strspn(line, " \t\n");
2370 char *next = strtok(p, " \t\n");
2373 if(nargc >= maxargs) {
2374 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2377 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2382 next = strtok(NULL, " \t\n");
2388 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2393 for(int i = 0; commands[i].command; i++) {
2394 if(!strcasecmp(nargv[argc], commands[i].command)) {
2395 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2401 #ifdef HAVE_READLINE
2407 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2420 int main(int argc, char *argv[]) {
2421 program_name = argv[0];
2425 if(!parse_options(argc, argv))
2429 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2430 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2443 static struct WSAData wsa_state;
2445 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2446 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2454 tty = isatty(0) && isatty(1);
2457 return cmd_shell(argc, argv);
2459 for(int i = 0; commands[i].command; i++) {
2460 if(!strcasecmp(argv[optind], commands[i].command))
2461 return commands[i].function(argc - optind, argv + optind);
2464 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);