2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2012 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"
40 #define mkdir(a, b) mkdir(a)
44 /* The name this program was run with. */
45 static char *program_name = NULL;
47 /* If nonzero, display usage information and exit. */
48 static bool show_help = false;
50 /* If nonzero, print the version on standard output and exit. */
51 static bool show_version = false;
53 static char *name = NULL;
54 static char *identname = NULL; /* program name for syslog */
55 static char *pidfilename = NULL; /* pid file location */
56 static char *confdir = NULL;
57 static char controlcookie[1024];
59 char *confbase = NULL;
60 static char *tinc_conf = NULL;
61 static char *hosts_dir = NULL;
63 // Horrible global variables...
66 static char line[4096];
70 static bool force = false;
71 static bool tty = true;
74 static struct WSAData wsa_state;
77 static struct option const long_options[] = {
78 {"config", required_argument, NULL, 'c'},
79 {"debug", optional_argument, NULL, 0},
80 {"no-detach", no_argument, NULL, 0},
81 {"mlock", no_argument, NULL, 0},
82 {"net", required_argument, NULL, 'n'},
83 {"help", no_argument, NULL, 1},
84 {"version", no_argument, NULL, 2},
85 {"pidfile", required_argument, NULL, 5},
86 {"logfile", required_argument, NULL, 0},
87 {"bypass-security", no_argument, NULL, 0},
88 {"chroot", no_argument, NULL, 0},
89 {"user", required_argument, NULL, 0},
90 {"option", required_argument, NULL, 0},
91 {"force", no_argument, NULL, 6},
95 static void version(void) {
96 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
97 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
98 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
99 "See the AUTHORS file for a complete list.\n\n"
100 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
101 "and you are welcome to redistribute it under certain conditions;\n"
102 "see the file COPYING for details.\n");
105 static void usage(bool status) {
107 fprintf(stderr, "Try `%s --help\' for more information.\n",
110 printf("Usage: %s [options] command\n\n", program_name);
111 printf("Valid options are:\n"
112 " -c, --config=DIR Read configuration options from DIR.\n"
113 " -n, --net=NETNAME Connect to net NETNAME.\n"
114 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
115 " --help Display this help and exit.\n"
116 " --version Output version information and exit.\n"
118 "Valid commands are:\n"
119 " init [name] Create initial configuration files.\n"
120 " config Change configuration:\n"
121 " [get] VARIABLE - print current value of VARIABLE\n"
122 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
123 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
124 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
125 " start [tincd options] Start tincd.\n"
126 " stop Stop tincd.\n"
127 " restart Restart tincd.\n"
128 " reload Partially reload configuration of running tincd.\n"
129 " pid Show PID of currently running tincd.\n"
130 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
131 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
132 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
133 " dump Dump a list of one of the following things:\n"
134 " nodes - all known nodes in the VPN\n"
135 " edges - all known connections in the VPN\n"
136 " subnets - all known subnets in the VPN\n"
137 " connections - all meta connections with ourself\n"
138 " graph - graph of the VPN in dotty format\n"
139 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
140 " purge Purge unreachable nodes\n"
141 " debug N Set debug level\n"
142 " retry Retry all outgoing connections\n"
143 " disconnect NODE Close meta connection with NODE\n"
145 " top Show real-time statistics\n"
147 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
148 " log [level] Dump log output [up to the specified level]\n"
149 " export Export host configuration of local node to standard output\n"
150 " export-all Export all host configuration files to standard output\n"
151 " import [--force] Import host configuration file(s) from standard input\n"
153 printf("Report bugs to tinc@tinc-vpn.org.\n");
157 static bool parse_options(int argc, char **argv) {
159 int option_index = 0;
161 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
163 case 0: /* long option */
166 case 'c': /* config file */
167 confbase = xstrdup(optarg);
170 case 'n': /* net name given */
171 netname = xstrdup(optarg);
174 case 1: /* show help */
178 case 2: /* show version */
182 case 5: /* open control socket here */
183 pidfilename = xstrdup(optarg);
199 if(!netname && (netname = getenv("NETNAME")))
200 netname = xstrdup(netname);
202 /* netname "." is special: a "top-level name" */
204 if(netname && (!*netname || !strcmp(netname, "."))) {
209 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
210 fprintf(stderr, "Invalid character in netname!\n");
217 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
223 /* Check stdin and stdout */
225 /* Ask for a file and/or directory name. */
226 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
230 if(fgets(buf, sizeof buf, stdin) == NULL) {
231 fprintf(stderr, "Error while reading stdin: %s\n",
236 size_t len = strlen(buf);
245 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
247 if(filename[0] != '/') {
249 /* The directory is a relative path or a filename. */
250 directory = get_current_dir_name();
251 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
255 umask(0077); /* Disallow everything for group and other */
257 /* Open it first to keep the inode busy */
259 r = fopen(filename, mode);
262 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
270 Generate a public/private ECDSA keypair, and ask for a file to store
273 static bool ecdsa_keygen(bool ask) {
278 fprintf(stderr, "Generating ECDSA keypair:\n");
280 if(!ecdsa_generate(&key)) {
281 fprintf(stderr, "Error during key generation!\n");
284 fprintf(stderr, "Done.\n");
286 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
287 f = ask_and_open(filename, "private ECDSA key", "a", ask);
293 /* Make it unreadable for others. */
294 fchmod(fileno(f), 0600);
298 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
300 ecdsa_write_pem_private_key(&key, f);
306 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
308 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
310 f = ask_and_open(filename, "public ECDSA key", "a", ask);
316 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
318 char *pubkey = ecdsa_get_base64_public_key(&key);
319 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
329 Generate a public/private RSA keypair, and ask for a file to store
332 static bool rsa_keygen(int bits, bool ask) {
337 fprintf(stderr, "Generating %d bits keys:\n", bits);
339 if(!rsa_generate(&key, bits, 0x10001)) {
340 fprintf(stderr, "Error during key generation!\n");
343 fprintf(stderr, "Done.\n");
345 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
346 f = ask_and_open(filename, "private RSA key", "a", ask);
352 /* Make it unreadable for others. */
353 fchmod(fileno(f), 0600);
357 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
359 rsa_write_pem_private_key(&key, f);
365 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
367 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
369 f = ask_and_open(filename, "public RSA key", "a", ask);
375 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
377 rsa_write_pem_public_key(&key, f);
386 Set all files and paths according to netname
388 static void make_names(void) {
391 char installdir[1024] = "";
392 long len = sizeof installdir;
396 xasprintf(&identname, "tinc.%s", netname);
398 identname = xstrdup("tinc");
401 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
402 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
405 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
407 xasprintf(&confbase, "%s", installdir);
411 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
417 confdir = xstrdup(CONFDIR);
420 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
424 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
426 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
429 xasprintf(&confbase, CONFDIR SLASH "tinc");
434 confdir = xstrdup(installdir);
437 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
438 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
441 static char buffer[4096];
442 static size_t blen = 0;
444 bool recvline(int fd, char *line, size_t len) {
445 char *newline = NULL;
447 while(!(newline = memchr(buffer, '\n', blen))) {
448 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
449 if(result == -1 && errno == EINTR)
456 if(newline - buffer >= len)
459 len = newline - buffer;
461 memcpy(line, buffer, len);
463 memmove(buffer, newline + 1, blen - len - 1);
469 static bool recvdata(int fd, char *data, size_t len) {
471 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
472 if(result == -1 && errno == EINTR)
479 memcpy(data, buffer, len);
480 memmove(buffer, buffer + len, blen - len);
486 bool sendline(int fd, char *format, ...) {
487 static char buffer[4096];
492 va_start(ap, format);
493 blen = vsnprintf(buffer, sizeof buffer, format, ap);
496 if(blen < 1 || blen >= sizeof buffer)
503 int result = send(fd, p, blen, 0);
504 if(result == -1 && errno == EINTR)
515 static void pcap(int fd, FILE *out, int snaplen) {
516 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
524 uint32_t tz_accuracy;
531 snaplen ?: sizeof data,
544 fwrite(&header, sizeof header, 1, out);
548 while(recvline(fd, line, sizeof line)) {
550 int n = sscanf(line, "%d %d %d", &code, &req, &len);
551 gettimeofday(&tv, NULL);
552 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
554 if(!recvdata(fd, data, len))
556 packet.tv_sec = tv.tv_sec;
557 packet.tv_usec = tv.tv_usec;
559 packet.origlen = len;
560 fwrite(&packet, sizeof packet, 1, out);
561 fwrite(data, len, 1, out);
566 static void logcontrol(int fd, FILE *out, int level) {
567 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
571 while(recvline(fd, line, sizeof line)) {
573 int n = sscanf(line, "%d %d %d", &code, &req, &len);
574 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
576 if(!recvdata(fd, data, len))
578 fwrite(data, len, 1, out);
585 static bool remove_service(void) {
586 SC_HANDLE manager = NULL;
587 SC_HANDLE service = NULL;
588 SERVICE_STATUS status = {0};
590 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
592 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
596 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
599 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
603 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
604 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
606 fprintf(stderr, "%s service stopped\n", identname);
608 if(!DeleteService(service)) {
609 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
613 fprintf(stderr, "%s service removed\n", identname);
619 static bool connect_tincd(bool verbose) {
623 FILE *f = fopen(pidfilename, "r");
626 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
633 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
635 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
643 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
645 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
650 struct addrinfo hints = {
651 .ai_family = AF_UNSPEC,
652 .ai_socktype = SOCK_STREAM,
653 .ai_protocol = IPPROTO_TCP,
657 struct addrinfo *res = NULL;
659 if(getaddrinfo(host, port, &hints, &res) || !res) {
661 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
665 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
668 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
673 unsigned long arg = 0;
675 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
677 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
681 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
683 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
692 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
694 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
698 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
700 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
702 fprintf(stderr, "Could not fully establish control socket connection\n");
710 static int cmd_start(int argc, char *argv[]) {
716 char *slash = strrchr(argv[0], '/');
719 if ((c = strrchr(argv[0], '\\')) > slash)
724 xasprintf(&c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
730 for(i = j = 1; argv[i]; ++i)
731 if (i != optind && strcmp(argv[i], "--") != 0)
736 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
740 static int cmd_stop(int argc, char *argv[]) {
742 if(!connect_tincd(true)) {
744 if(kill(pid, SIGTERM))
746 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
753 sendline(fd, "%d %d", CONTROL, REQ_STOP);
754 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
755 fprintf(stderr, "Could not stop tinc daemon.\n");
759 if(!remove_service())
765 static int cmd_restart(int argc, char *argv[]) {
766 cmd_stop(argc, argv);
767 return cmd_start(argc, argv);
770 static int cmd_reload(int argc, char *argv[]) {
771 if(!connect_tincd(true))
774 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
775 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
776 fprintf(stderr, "Could not reload configuration.\n");
784 static int cmd_dump(int argc, char *argv[]) {
786 fprintf(stderr, "Invalid number of arguments.\n");
791 if(!connect_tincd(true))
794 bool do_graph = false;
796 if(!strcasecmp(argv[1], "nodes"))
797 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
798 else if(!strcasecmp(argv[1], "edges"))
799 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
800 else if(!strcasecmp(argv[1], "subnets"))
801 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
802 else if(!strcasecmp(argv[1], "connections"))
803 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
804 else if(!strcasecmp(argv[1], "graph")) {
805 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
806 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
809 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
815 printf("digraph {\n");
817 while(recvline(fd, line, sizeof line)) {
818 char node1[4096], node2[4096];
819 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
821 if(do_graph && req == REQ_DUMP_NODES)
833 printf("%s\n", line + 5);
835 if(req == REQ_DUMP_NODES)
836 printf(" %s [label = \"%s\"];\n", node1, node1);
838 printf(" %s -> %s;\n", node1, node2);
842 fprintf(stderr, "Error receiving dump.\n");
846 static int cmd_purge(int argc, char *argv[]) {
847 if(!connect_tincd(true))
850 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
851 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
852 fprintf(stderr, "Could not purge old information.\n");
859 static int cmd_debug(int argc, char *argv[]) {
861 fprintf(stderr, "Invalid number of arguments.\n");
865 if(!connect_tincd(true))
868 int debuglevel = atoi(argv[1]);
871 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
872 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
873 fprintf(stderr, "Could not set debug level.\n");
877 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
881 static int cmd_retry(int argc, char *argv[]) {
882 if(!connect_tincd(true))
885 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
886 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
887 fprintf(stderr, "Could not retry outgoing connections.\n");
894 static int cmd_connect(int argc, char *argv[]) {
896 fprintf(stderr, "Invalid number of arguments.\n");
900 if(!check_id(argv[2])) {
901 fprintf(stderr, "Invalid name for node.\n");
905 if(!connect_tincd(true))
908 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
909 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
910 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
917 static int cmd_disconnect(int argc, char *argv[]) {
919 fprintf(stderr, "Invalid number of arguments.\n");
923 if(!check_id(argv[2])) {
924 fprintf(stderr, "Invalid name for node.\n");
928 if(!connect_tincd(true))
931 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
932 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
933 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
940 static int cmd_top(int argc, char *argv[]) {
942 if(!connect_tincd(true))
948 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
953 static int cmd_pcap(int argc, char *argv[]) {
954 if(!connect_tincd(true))
957 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
961 static int cmd_log(int argc, char *argv[]) {
962 if(!connect_tincd(true))
965 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
969 static int cmd_pid(int argc, char *argv[]) {
970 if(!connect_tincd(true) && !pid)
977 static int rstrip(char *value) {
978 int len = strlen(value);
979 while(len && strchr("\t\r\n ", value[len - 1]))
984 static char *get_my_name() {
985 FILE *f = fopen(tinc_conf, "r");
987 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
993 while(fgets(buf, sizeof buf, f)) {
994 int len = strcspn(buf, "\t =");
996 value += strspn(value, "\t ");
999 value += strspn(value, "\t ");
1004 if(strcasecmp(buf, "Name"))
1008 return strdup(value);
1013 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1017 #define VAR_SERVER 1 /* Should be in tinc.conf */
1018 #define VAR_HOST 2 /* Can be in host config file */
1019 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1020 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1025 } const variables[] = {
1026 /* Server configuration */
1027 {"AddressFamily", VAR_SERVER},
1028 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1029 {"BindToInterface", VAR_SERVER},
1030 {"Broadcast", VAR_SERVER},
1031 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1032 {"DecrementTTL", VAR_SERVER},
1033 {"Device", VAR_SERVER},
1034 {"DeviceType", VAR_SERVER},
1035 {"DirectOnly", VAR_SERVER},
1036 {"ECDSAPrivateKeyFile", VAR_SERVER},
1037 {"ExperimentalProtocol", VAR_SERVER},
1038 {"Forwarding", VAR_SERVER},
1039 {"GraphDumpFile", VAR_SERVER},
1040 {"Hostnames", VAR_SERVER},
1041 {"IffOneQueue", VAR_SERVER},
1042 {"Interface", VAR_SERVER},
1043 {"KeyExpire", VAR_SERVER},
1044 {"LocalDiscovery", VAR_SERVER},
1045 {"MACExpire", VAR_SERVER},
1046 {"MaxOutputBufferSize", VAR_SERVER},
1047 {"MaxTimeout", VAR_SERVER},
1048 {"Mode", VAR_SERVER},
1049 {"Name", VAR_SERVER},
1050 {"PingInterval", VAR_SERVER},
1051 {"PingTimeout", VAR_SERVER},
1052 {"PriorityInheritance", VAR_SERVER},
1053 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1054 {"PrivateKeyFile", VAR_SERVER},
1055 {"ProcessPriority", VAR_SERVER},
1056 {"Proxy", VAR_SERVER},
1057 {"ReplayWindow", VAR_SERVER},
1058 {"StrictSubnets", VAR_SERVER},
1059 {"TunnelServer", VAR_SERVER},
1060 {"UDPRcvBuf", VAR_SERVER},
1061 {"UDPSndBuf", VAR_SERVER},
1062 {"VDEGroup", VAR_SERVER},
1063 {"VDEPort", VAR_SERVER},
1064 /* Host configuration */
1065 {"Address", VAR_HOST | VAR_MULTIPLE},
1066 {"Cipher", VAR_SERVER | VAR_HOST},
1067 {"ClampMSS", VAR_SERVER | VAR_HOST},
1068 {"Compression", VAR_SERVER | VAR_HOST},
1069 {"Digest", VAR_SERVER | VAR_HOST},
1070 {"ECDSAPublicKey", VAR_HOST},
1071 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1072 {"IndirectData", VAR_SERVER | VAR_HOST},
1073 {"MACLength", VAR_SERVER | VAR_HOST},
1074 {"PMTU", VAR_SERVER | VAR_HOST},
1075 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1077 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1078 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1079 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1080 {"TCPOnly", VAR_SERVER | VAR_HOST},
1081 {"Weight", VAR_HOST},
1085 static int cmd_config(int argc, char *argv[]) {
1087 fprintf(stderr, "Invalid number of arguments.\n");
1092 if(!strcasecmp(argv[1], "get")) {
1094 } else if(!strcasecmp(argv[1], "add")) {
1095 argv++, argc--, action = 1;
1096 } else if(!strcasecmp(argv[1], "del")) {
1097 argv++, argc--, action = -1;
1098 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1099 argv++, argc--, action = 0;
1103 fprintf(stderr, "Invalid number of arguments.\n");
1107 // Concatenate the rest of the command line
1108 strncpy(line, argv[1], sizeof line - 1);
1109 for(int i = 2; i < argc; i++) {
1110 strncat(line, " ", sizeof line - 1 - strlen(line));
1111 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1114 // Liberal parsing into node name, variable name and value.
1120 len = strcspn(line, "\t =");
1122 value += strspn(value, "\t ");
1125 value += strspn(value, "\t ");
1128 variable = strchr(line, '.');
1137 fprintf(stderr, "No variable given.\n");
1141 if(action >= 0 && !*value) {
1142 fprintf(stderr, "No value for variable given.\n");
1146 if(action < -1 && *value)
1149 /* Some simple checks. */
1152 for(int i = 0; variables[i].name; i++) {
1153 if(strcasecmp(variables[i].name, variable))
1157 variable = (char *)variables[i].name;
1159 /* Discourage use of obsolete variables. */
1161 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1163 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1165 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1170 /* Don't put server variables in host config files */
1172 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1174 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1176 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1181 /* Should this go into our own host config file? */
1183 if(!node && !(variables[i].type & VAR_SERVER)) {
1184 node = get_my_name();
1192 if(node && !check_id(node)) {
1193 fprintf(stderr, "Invalid name for node.\n");
1198 if(force || action < 0) {
1199 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1201 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1206 // Open the right configuration file.
1209 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1211 filename = tinc_conf;
1213 FILE *f = fopen(filename, "r");
1215 if(action < 0 || errno != ENOENT) {
1216 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1220 // If it doesn't exist, create it.
1221 f = fopen(filename, "a+");
1223 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1226 fprintf(stderr, "Created configuration file %s.\n", filename);
1230 char *tmpfile = NULL;
1234 xasprintf(&tmpfile, "%s.config.tmp", filename);
1235 tf = fopen(tmpfile, "w");
1237 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1243 // Copy the file, making modifications on the fly, unless we are just getting a value.
1247 bool removed = false;
1250 while(fgets(buf1, sizeof buf1, f)) {
1251 buf1[sizeof buf1 - 1] = 0;
1252 strncpy(buf2, buf1, sizeof buf2);
1254 // Parse line in a simple way
1258 len = strcspn(buf2, "\t =");
1259 bvalue = buf2 + len;
1260 bvalue += strspn(bvalue, "\t ");
1261 if(*bvalue == '=') {
1263 bvalue += strspn(bvalue, "\t ");
1269 if(!strcasecmp(buf2, variable)) {
1273 printf("%s\n", bvalue);
1275 } else if(action == -1) {
1276 if(!*value || !strcasecmp(bvalue, value)) {
1281 } else if(action == 0) {
1282 // Already set? Delete the rest...
1285 // Otherwise, replace.
1286 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1287 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1296 // Copy original line...
1297 if(fputs(buf1, tf) < 0) {
1298 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1302 // Add newline if it is missing...
1303 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1304 if(fputc('\n', tf) < 0) {
1305 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1312 // Make sure we read everything...
1313 if(ferror(f) || !feof(f)) {
1314 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1319 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1323 // Add new variable if necessary.
1324 if(action > 0 || (action == 0 && !set)) {
1325 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1326 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1333 fprintf(stderr, "No matching configuration variables found.\n");
1337 // Make sure we wrote everything...
1339 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1343 // Could we find what we had to remove?
1344 if(action < 0 && !removed) {
1346 fprintf(stderr, "No configuration variables deleted.\n");
1350 // Replace the configuration file with the new one
1352 if(remove(filename)) {
1353 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1357 if(rename(tmpfile, filename)) {
1358 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1362 // Silently try notifying a running tincd of changes.
1363 if(connect_tincd(false))
1364 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1369 bool check_id(const char *name) {
1373 for(int i = 0; i < strlen(name); i++) {
1374 if(!isalnum(name[i]) && name[i] != '_')
1381 static int cmd_init(int argc, char *argv[]) {
1382 if(!access(tinc_conf, F_OK)) {
1383 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1390 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1392 if(!fgets(buf, sizeof buf, stdin)) {
1393 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1396 int len = rstrip(buf);
1398 fprintf(stderr, "No name given!\n");
1403 fprintf(stderr, "No Name given!\n");
1407 name = strdup(argv[1]);
1409 fprintf(stderr, "No Name given!\n");
1414 if(!check_id(name)) {
1415 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1419 if(mkdir(confdir, 0755) && errno != EEXIST) {
1420 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1424 if(mkdir(confbase, 0755) && errno != EEXIST) {
1425 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1429 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1430 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1434 FILE *f = fopen(tinc_conf, "w");
1436 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1440 fprintf(f, "Name = %s\n", name);
1443 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1448 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1449 if(access(filename, F_OK)) {
1450 FILE *f = fopen(filename, "w");
1452 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1455 fchmod(fileno(f), 0755);
1456 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1465 static int cmd_generate_keys(int argc, char *argv[]) {
1466 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1469 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1470 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1473 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1474 return !ecdsa_keygen(true);
1477 static int cmd_help(int argc, char *argv[]) {
1482 static int cmd_version(int argc, char *argv[]) {
1487 static int cmd_info(int argc, char *argv[]) {
1489 fprintf(stderr, "Invalid number of arguments.\n");
1493 if(!connect_tincd(true))
1496 return info(fd, argv[1]);
1499 static const char *conffiles[] = {
1510 static int cmd_edit(int argc, char *argv[]) {
1512 fprintf(stderr, "Invalid number of arguments.\n");
1516 char *filename = NULL;
1518 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1519 for(int i = 0; conffiles[i]; i++) {
1520 if(!strcmp(argv[1], conffiles[i])) {
1521 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1530 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1531 char *dash = strchr(argv[1], '-');
1534 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1535 fprintf(stderr, "Invalid configuration filename.\n");
1543 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1545 xasprintf(&command, "edit \"%s\"", filename);
1547 int result = system(command);
1551 // Silently try notifying a running tincd of changes.
1552 if(connect_tincd(false))
1553 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1558 static int export(const char *name, FILE *out) {
1560 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1561 FILE *in = fopen(filename, "r");
1563 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1567 fprintf(out, "Name = %s\n", name);
1569 while(fgets(buf, sizeof buf, in)) {
1570 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1575 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1584 static int cmd_export(int argc, char *argv[]) {
1585 char *name = get_my_name();
1589 return export(name, stdout);
1592 static int cmd_export_all(int argc, char *argv[]) {
1593 DIR *dir = opendir(hosts_dir);
1595 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1603 while((ent = readdir(dir))) {
1604 if(!check_id(ent->d_name))
1610 printf("#---------------------------------------------------------------#\n");
1612 result |= export(ent->d_name, stdout);
1619 static int cmd_import(int argc, char *argv[]) {
1627 bool firstline = true;
1629 while(fgets(buf, sizeof buf, in)) {
1630 if(sscanf(buf, "Name = %s", name) == 1) {
1631 if(!check_id(name)) {
1632 fprintf(stderr, "Invalid Name in input!\n");
1640 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1642 if(!force && !access(filename, F_OK)) {
1643 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1648 out = fopen(filename, "w");
1650 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1657 } else if(firstline) {
1658 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1663 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1667 if(fputs(buf, out) < 0) {
1668 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1678 fprintf(stderr, "Imported %d host configuration files.\n", count);
1681 fprintf(stderr, "No host configuration files imported.\n");
1686 static const struct {
1687 const char *command;
1688 int (*function)(int argc, char *argv[]);
1690 {"start", cmd_start},
1692 {"restart", cmd_restart},
1693 {"reload", cmd_reload},
1695 {"purge", cmd_purge},
1696 {"debug", cmd_debug},
1697 {"retry", cmd_retry},
1698 {"connect", cmd_connect},
1699 {"disconnect", cmd_disconnect},
1704 {"config", cmd_config},
1706 {"generate-keys", cmd_generate_keys},
1707 {"generate-rsa-keys", cmd_generate_rsa_keys},
1708 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1710 {"version", cmd_version},
1713 {"export", cmd_export},
1714 {"export-all", cmd_export_all},
1715 {"import", cmd_import},
1719 #ifdef HAVE_READLINE
1720 static char *complete_command(const char *text, int state) {
1728 while(commands[i].command) {
1729 if(!strncasecmp(commands[i].command, text, strlen(text)))
1730 return xstrdup(commands[i].command);
1737 static char *complete_dump(const char *text, int state) {
1738 const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1747 if(!strncasecmp(matches[i], text, strlen(text)))
1748 return xstrdup(matches[i]);
1755 static char **completion (const char *text, int start, int end) {
1756 char **matches = NULL;
1759 matches = rl_completion_matches(text, complete_command);
1760 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
1761 matches = rl_completion_matches(text, complete_dump);
1767 static int cmd_shell(int argc, char *argv[]) {
1769 xasprintf(&prompt, "%s> ", identname);
1773 int maxargs = argc + 16;
1774 char **nargv = xmalloc(maxargs * sizeof *nargv);
1777 for(int i = 0; i < argc; i++)
1780 #ifdef HAVE_READLINE
1781 rl_readline_name = "tinc";
1782 rl_attempted_completion_function = completion;
1783 rl_filename_completion_desired = 0;
1788 #ifdef HAVE_READLINE
1792 line = readline(prompt);
1794 copy = xstrdup(line);
1796 line = fgets(buf, sizeof buf, stdin);
1800 fputs(stdout, prompt);
1802 line = fgets(buf, sizeof buf, stdin);
1808 /* Ignore comments */
1816 char *p = line + strspn(line, " \t\n");
1817 char *next = strtok(p, " \t\n");
1820 if(nargc >= maxargs) {
1821 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
1824 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
1829 next = strtok(NULL, " \t\n");
1837 for(int i = 0; commands[i].command; i++) {
1838 if(!strcasecmp(nargv[argc], commands[i].command)) {
1839 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
1845 #ifdef HAVE_READLINE
1851 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
1862 int main(int argc, char *argv[]) {
1863 program_name = argv[0];
1865 if(!parse_options(argc, argv))
1880 tty = isatty(0) && isatty(1);
1883 return cmd_shell(argc, argv);
1885 for(int i = 0; commands[i].command; i++) {
1886 if(!strcasecmp(argv[optind], commands[i].command))
1887 return commands[i].function(argc - optind, argv + optind);
1890 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);