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.
26 #include "control_common.h"
35 #define mkdir(a, b) mkdir(a)
38 /* The name this program was run with. */
39 static char *program_name = NULL;
41 /* If nonzero, display usage information and exit. */
42 static bool show_help = false;
44 /* If nonzero, print the version on standard output and exit. */
45 static bool show_version = false;
47 static char *name = NULL;
48 static char *identname = NULL; /* program name for syslog */
49 static char *pidfilename = NULL; /* pid file location */
50 static char controlcookie[1024];
52 char *confbase = NULL;
53 static char *tinc_conf = NULL;
54 static char *hosts_dir = NULL;
56 // Horrible global variables...
59 static char line[4096];
63 static bool force = false;
66 static struct WSAData wsa_state;
69 static struct option const long_options[] = {
70 {"config", required_argument, NULL, 'c'},
71 {"debug", optional_argument, NULL, 0},
72 {"no-detach", no_argument, NULL, 0},
73 {"mlock", no_argument, NULL, 0},
74 {"net", required_argument, NULL, 'n'},
75 {"help", no_argument, NULL, 1},
76 {"version", no_argument, NULL, 2},
77 {"pidfile", required_argument, NULL, 5},
78 {"logfile", required_argument, NULL, 0},
79 {"bypass-security", no_argument, NULL, 0},
80 {"chroot", no_argument, NULL, 0},
81 {"user", required_argument, NULL, 0},
82 {"option", required_argument, NULL, 0},
83 {"force", no_argument, NULL, 6},
87 static void version(void) {
88 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
89 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
90 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
91 "See the AUTHORS file for a complete list.\n\n"
92 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
93 "and you are welcome to redistribute it under certain conditions;\n"
94 "see the file COPYING for details.\n");
97 static void usage(bool status) {
99 fprintf(stderr, "Try `%s --help\' for more information.\n",
102 printf("Usage: %s [options] command\n\n", program_name);
103 printf("Valid options are:\n"
104 " -c, --config=DIR Read configuration options from DIR.\n"
105 " -n, --net=NETNAME Connect to net NETNAME.\n"
106 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
107 " --help Display this help and exit.\n"
108 " --version Output version information and exit.\n"
110 "Valid commands are:\n"
111 " init [name] Create initial configuration files.\n"
112 " config Change configuration:\n"
113 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
114 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
115 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
116 " start [tincd options] Start tincd.\n"
117 " stop Stop tincd.\n"
118 " restart Restart tincd.\n"
119 " reload Partially reload configuration of running tincd.\n"
120 " pid Show PID of currently running tincd.\n"
121 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
122 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
123 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
124 " dump Dump a list of one of the following things:\n"
125 " nodes - all known nodes in the VPN\n"
126 " edges - all known connections in the VPN\n"
127 " subnets - all known subnets in the VPN\n"
128 " connections - all meta connections with ourself\n"
129 " graph - graph of the VPN in dotty format\n"
130 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
131 " purge Purge unreachable nodes\n"
132 " debug N Set debug level\n"
133 " retry Retry all outgoing connections\n"
134 " disconnect NODE Close meta connection with NODE\n"
136 " top Show real-time statistics\n"
138 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
139 " log [level] Dump log output [up to the specified level]\n"
140 " export Export host configuration of local node to standard output\n"
141 " export-all Export all host configuration files to standard output\n"
142 " import [--force] Import host configuration file(s) from standard input\n"
144 printf("Report bugs to tinc@tinc-vpn.org.\n");
148 static bool parse_options(int argc, char **argv) {
150 int option_index = 0;
152 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
154 case 0: /* long option */
157 case 'c': /* config file */
158 confbase = xstrdup(optarg);
161 case 'n': /* net name given */
162 netname = xstrdup(optarg);
165 case 1: /* show help */
169 case 2: /* show version */
173 case 5: /* open control socket here */
174 pidfilename = xstrdup(optarg);
190 if(!netname && (netname = getenv("NETNAME")))
191 netname = xstrdup(netname);
193 /* netname "." is special: a "top-level name" */
195 if(netname && !strcmp(netname, ".")) {
203 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
209 /* Check stdin and stdout */
210 if(isatty(0) && isatty(1)) {
211 /* Ask for a file and/or directory name. */
212 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
216 if(fgets(buf, sizeof buf, stdin) == NULL) {
217 fprintf(stderr, "Error while reading stdin: %s\n",
222 size_t len = strlen(buf);
231 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
233 if(filename[0] != '/') {
235 /* The directory is a relative path or a filename. */
236 directory = get_current_dir_name();
237 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
241 umask(0077); /* Disallow everything for group and other */
243 /* Open it first to keep the inode busy */
245 r = fopen(filename, mode);
248 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
256 Generate a public/private ECDSA keypair, and ask for a file to store
259 static bool ecdsa_keygen() {
264 fprintf(stderr, "Generating ECDSA keypair:\n");
266 if(!ecdsa_generate(&key)) {
267 fprintf(stderr, "Error during key generation!\n");
270 fprintf(stderr, "Done.\n");
272 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
273 f = ask_and_open(filename, "private ECDSA key", "a");
279 /* Make it unreadable for others. */
280 fchmod(fileno(f), 0600);
284 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
286 ecdsa_write_pem_private_key(&key, f);
292 xasprintf(&filename, "%s/hosts/%s", confbase, name);
294 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
296 f = ask_and_open(filename, "public ECDSA key", "a");
302 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
304 char *pubkey = ecdsa_get_base64_public_key(&key);
305 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
315 Generate a public/private RSA keypair, and ask for a file to store
318 static bool rsa_keygen(int bits) {
323 fprintf(stderr, "Generating %d bits keys:\n", bits);
325 if(!rsa_generate(&key, bits, 0x10001)) {
326 fprintf(stderr, "Error during key generation!\n");
329 fprintf(stderr, "Done.\n");
331 xasprintf(&filename, "%s/rsa_key.priv", confbase);
332 f = ask_and_open(filename, "private RSA key", "a");
338 /* Make it unreadable for others. */
339 fchmod(fileno(f), 0600);
343 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
345 rsa_write_pem_private_key(&key, f);
351 xasprintf(&filename, "%s/hosts/%s", confbase, name);
353 xasprintf(&filename, "%s/rsa_key.pub", confbase);
355 f = ask_and_open(filename, "public RSA key", "a");
361 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
363 rsa_write_pem_public_key(&key, f);
372 Set all files and paths according to netname
374 static void make_names(void) {
377 char installdir[1024] = "";
378 long len = sizeof installdir;
382 xasprintf(&identname, "tinc.%s", netname);
384 identname = xstrdup("tinc");
387 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
388 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
391 xasprintf(&confbase, "%s/%s", installdir, netname);
393 xasprintf(&confbase, "%s", installdir);
397 xasprintf(&pidfilename, "%s/pid", confbase);
405 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
409 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
411 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
414 xasprintf(&confbase, CONFDIR "/tinc");
421 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
422 xasprintf(&hosts_dir, "%s/hosts", confbase);
425 static char buffer[4096];
426 static size_t blen = 0;
428 bool recvline(int fd, char *line, size_t len) {
429 char *newline = NULL;
431 while(!(newline = memchr(buffer, '\n', blen))) {
432 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
433 if(result == -1 && errno == EINTR)
440 if(newline - buffer >= len)
443 len = newline - buffer;
445 memcpy(line, buffer, len);
447 memmove(buffer, newline + 1, blen - len - 1);
453 static bool recvdata(int fd, char *data, size_t len) {
455 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
456 if(result == -1 && errno == EINTR)
463 memcpy(data, buffer, len);
464 memmove(buffer, buffer + len, blen - len);
470 bool sendline(int fd, char *format, ...) {
471 static char buffer[4096];
476 va_start(ap, format);
477 blen = vsnprintf(buffer, sizeof buffer, format, ap);
480 if(blen < 1 || blen >= sizeof buffer)
487 int result = send(fd, p, blen, 0);
488 if(result == -1 && errno == EINTR)
499 static void pcap(int fd, FILE *out, int snaplen) {
500 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
508 uint32_t tz_accuracy;
515 snaplen ?: sizeof data,
528 fwrite(&header, sizeof header, 1, out);
532 while(recvline(fd, line, sizeof line)) {
534 int n = sscanf(line, "%d %d %d", &code, &req, &len);
535 gettimeofday(&tv, NULL);
536 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
538 if(!recvdata(fd, data, len))
540 packet.tv_sec = tv.tv_sec;
541 packet.tv_usec = tv.tv_usec;
543 packet.origlen = len;
544 fwrite(&packet, sizeof packet, 1, out);
545 fwrite(data, len, 1, out);
550 static void logcontrol(int fd, FILE *out, int level) {
551 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
555 while(recvline(fd, line, sizeof line)) {
557 int n = sscanf(line, "%d %d %d", &code, &req, &len);
558 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
560 if(!recvdata(fd, data, len))
562 fwrite(data, len, 1, out);
569 static bool remove_service(void) {
570 SC_HANDLE manager = NULL;
571 SC_HANDLE service = NULL;
572 SERVICE_STATUS status = {0};
574 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
576 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
580 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
583 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
587 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
588 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
590 fprintf(stderr, "%s service stopped\n", identname);
592 if(!DeleteService(service)) {
593 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
597 fprintf(stderr, "%s service removed\n", identname);
603 static bool connect_tincd() {
607 FILE *f = fopen(pidfilename, "r");
609 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
616 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
617 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
622 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
623 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
628 struct addrinfo hints = {
629 .ai_family = AF_UNSPEC,
630 .ai_socktype = SOCK_STREAM,
631 .ai_protocol = IPPROTO_TCP,
635 struct addrinfo *res = NULL;
637 if(getaddrinfo(host, port, &hints, &res) || !res) {
638 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
642 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
644 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
649 unsigned long arg = 0;
651 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
652 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
656 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
657 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
666 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
667 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
671 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
673 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
674 fprintf(stderr, "Could not fully establish control socket connection\n");
682 static int cmd_start(int argc, char *argv[]) {
688 char *slash = strrchr(argv[0], '/');
691 if ((c = strrchr(argv[0], '\\')) > slash)
696 xasprintf(&c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
702 for(i = j = 1; argv[i]; ++i)
703 if (i != optind && strcmp(argv[i], "--") != 0)
708 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
712 static int cmd_stop(int argc, char *argv[]) {
717 sendline(fd, "%d %d", CONTROL, REQ_STOP);
718 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
719 fprintf(stderr, "Could not stop tinc daemon.\n");
723 if(!remove_service())
729 static int cmd_restart(int argc, char *argv[]) {
730 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
733 static int cmd_reload(int argc, char *argv[]) {
737 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
738 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
739 fprintf(stderr, "Could not reload configuration.\n");
747 static int cmd_dump(int argc, char *argv[]) {
749 fprintf(stderr, "Invalid number of arguments.\n");
757 bool do_graph = false;
759 if(!strcasecmp(argv[1], "nodes"))
760 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
761 else if(!strcasecmp(argv[1], "edges"))
762 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
763 else if(!strcasecmp(argv[1], "subnets"))
764 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
765 else if(!strcasecmp(argv[1], "connections"))
766 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
767 else if(!strcasecmp(argv[1], "graph")) {
768 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
769 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
772 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
778 printf("digraph {\n");
780 while(recvline(fd, line, sizeof line)) {
781 char node1[4096], node2[4096];
782 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
784 if(do_graph && req == REQ_DUMP_NODES)
796 printf("%s\n", line + 5);
798 if(req == REQ_DUMP_NODES)
799 printf(" %s [label = \"%s\"];\n", node1, node1);
801 printf(" %s -> %s;\n", node1, node2);
805 fprintf(stderr, "Error receiving dump.\n");
809 static int cmd_purge(int argc, char *argv[]) {
813 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
814 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
815 fprintf(stderr, "Could not purge old information.\n");
822 static int cmd_debug(int argc, char *argv[]) {
824 fprintf(stderr, "Invalid number of arguments.\n");
831 int debuglevel = atoi(argv[1]);
834 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
835 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
836 fprintf(stderr, "Could not set debug level.\n");
840 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
844 static int cmd_retry(int argc, char *argv[]) {
848 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
849 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
850 fprintf(stderr, "Could not retry outgoing connections.\n");
857 static int cmd_connect(int argc, char *argv[]) {
859 fprintf(stderr, "Invalid number of arguments.\n");
863 if(!check_id(argv[2])) {
864 fprintf(stderr, "Invalid name for node.\n");
871 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
872 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
873 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
880 static int cmd_disconnect(int argc, char *argv[]) {
882 fprintf(stderr, "Invalid number of arguments.\n");
886 if(!check_id(argv[2])) {
887 fprintf(stderr, "Invalid name for node.\n");
894 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
895 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
896 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
903 static int cmd_top(int argc, char *argv[]) {
911 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
916 static int cmd_pcap(int argc, char *argv[]) {
920 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
924 static int cmd_log(int argc, char *argv[]) {
928 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
932 static int cmd_pid(int argc, char *argv[]) {
940 static int rstrip(char *value) {
941 int len = strlen(value);
942 while(len && strchr("\t\r\n ", value[len - 1]))
947 static char *get_my_name() {
948 FILE *f = fopen(tinc_conf, "r");
950 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
956 while(fgets(buf, sizeof buf, f)) {
957 int len = strcspn(buf, "\t =");
959 value += strspn(value, "\t ");
962 value += strspn(value, "\t ");
967 if(strcasecmp(buf, "Name"))
971 return strdup(value);
976 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
980 #define VAR_SERVER 1 /* Should be in tinc.conf */
981 #define VAR_HOST 2 /* Can be in host config file */
982 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
983 #define VAR_OBSOLETE 8 /* Should not be used anymore */
988 } const variables[] = {
989 /* Server configuration */
990 {"AddressFamily", VAR_SERVER},
991 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
992 {"BindToInterface", VAR_SERVER},
993 {"Broadcast", VAR_SERVER},
994 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
995 {"DecrementTTL", VAR_SERVER},
996 {"Device", VAR_SERVER},
997 {"DeviceType", VAR_SERVER},
998 {"DirectOnly", VAR_SERVER},
999 {"ECDSAPrivateKeyFile", VAR_SERVER},
1000 {"ExperimentalProtocol", VAR_SERVER},
1001 {"Forwarding", VAR_SERVER},
1002 {"GraphDumpFile", VAR_SERVER},
1003 {"Hostnames", VAR_SERVER},
1004 {"IffOneQueue", VAR_SERVER},
1005 {"Interface", VAR_SERVER},
1006 {"KeyExpire", VAR_SERVER},
1007 {"LocalDiscovery", VAR_SERVER},
1008 {"MACExpire", VAR_SERVER},
1009 {"MaxTimeout", VAR_SERVER},
1010 {"Mode", VAR_SERVER},
1011 {"Name", VAR_SERVER},
1012 {"PingInterval", VAR_SERVER},
1013 {"PingTimeout", VAR_SERVER},
1014 {"PriorityInheritance", VAR_SERVER},
1015 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1016 {"PrivateKeyFile", VAR_SERVER},
1017 {"ProcessPriority", VAR_SERVER},
1018 {"ReplayWindow", VAR_SERVER},
1019 {"StrictSubnets", VAR_SERVER},
1020 {"TunnelServer", VAR_SERVER},
1021 {"UDPRcvBuf", VAR_SERVER},
1022 {"UDPSndBuf", VAR_SERVER},
1023 /* Host configuration */
1024 {"Address", VAR_HOST | VAR_MULTIPLE},
1025 {"Cipher", VAR_SERVER | VAR_HOST},
1026 {"ClampMSS", VAR_SERVER | VAR_HOST},
1027 {"Compression", VAR_SERVER | VAR_HOST},
1028 {"Digest", VAR_SERVER | VAR_HOST},
1029 {"IndirectData", VAR_SERVER | VAR_HOST},
1030 {"MACLength", VAR_SERVER | VAR_HOST},
1031 {"PMTU", VAR_SERVER | VAR_HOST},
1032 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1034 {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1035 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1036 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1037 {"TCPOnly", VAR_SERVER | VAR_HOST},
1041 static int cmd_config(int argc, char *argv[]) {
1043 fprintf(stderr, "Invalid number of arguments.\n");
1048 if(!strcasecmp(argv[1], "add")) {
1049 argv++, argc--, action = 1;
1050 } else if(!strcasecmp(argv[1], "del")) {
1051 argv++, argc--, action = -1;
1052 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1053 argv++, argc--, action = 0;
1057 fprintf(stderr, "Invalid number of arguments.\n");
1061 // Concatenate the rest of the command line
1062 strncpy(line, argv[1], sizeof line - 1);
1063 for(int i = 2; i < argc; i++) {
1064 strncat(line, " ", sizeof line - 1 - strlen(line));
1065 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1068 // Liberal parsing into node name, variable name and value.
1074 len = strcspn(line, "\t =");
1076 value += strspn(value, "\t ");
1079 value += strspn(value, "\t ");
1082 variable = strchr(line, '.');
1091 fprintf(stderr, "No variable given.\n");
1095 if(action >= 0 && !*value) {
1096 fprintf(stderr, "No value for variable given.\n");
1100 /* Some simple checks. */
1103 for(int i = 0; variables[i].name; i++) {
1104 if(strcasecmp(variables[i].name, variable))
1108 variable = (char *)variables[i].name;
1110 /* Discourage use of obsolete variables. */
1112 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1114 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1116 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1121 /* Don't put server variables in host config files */
1123 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1125 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1127 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1132 /* Should this go into our own host config file? */
1134 if(!node && !(variables[i].type & VAR_SERVER)) {
1135 node = get_my_name();
1143 if(node && !check_id(node)) {
1144 fprintf(stderr, "Invalid name for node.\n");
1148 if(!found && action >= 0) {
1150 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1152 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1157 // Open the right configuration file.
1160 xasprintf(&filename, "%s/%s", hosts_dir, node);
1162 filename = tinc_conf;
1164 FILE *f = fopen(filename, "r");
1166 if(action < 0 || errno != ENOENT) {
1167 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1171 // If it doesn't exist, create it.
1172 f = fopen(filename, "a+");
1174 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1177 fprintf(stderr, "Created configuration file %s.\n", filename);
1182 xasprintf(&tmpfile, "%s.config.tmp", filename);
1183 FILE *tf = fopen(tmpfile, "w");
1185 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1189 // Copy the file, making modifications on the fly.
1193 bool removed = false;
1195 while(fgets(buf1, sizeof buf1, f)) {
1196 buf1[sizeof buf1 - 1] = 0;
1197 strncpy(buf2, buf1, sizeof buf2);
1199 // Parse line in a simple way
1203 len = strcspn(buf2, "\t =");
1204 bvalue = buf2 + len;
1205 bvalue += strspn(bvalue, "\t ");
1206 if(*bvalue == '=') {
1208 bvalue += strspn(bvalue, "\t ");
1214 if(!strcasecmp(buf2, variable)) {
1217 if(!*value || !strcasecmp(bvalue, value)) {
1222 } else if(action == 0) {
1223 // Already set? Delete the rest...
1226 // Otherwise, replace.
1227 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1228 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1236 // Copy original line...
1237 if(fputs(buf1, tf) < 0) {
1238 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1242 // Add newline if it is missing...
1243 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1244 if(fputc('\n', tf) < 0) {
1245 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1251 // Make sure we read everything...
1252 if(ferror(f) || !feof(f)) {
1253 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1258 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1262 // Add new variable if necessary.
1263 if(action > 0 || (action == 0 && !set)) {
1264 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1265 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1270 // Make sure we wrote everything...
1272 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1276 // Could we find what we had to remove?
1277 if(action < 0 && !removed) {
1279 fprintf(stderr, "No configuration variables deleted.\n");
1283 // Replace the configuration file with the new one
1285 if(remove(filename)) {
1286 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1290 if(rename(tmpfile, filename)) {
1291 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1295 // Silently try notifying a running tincd of changes.
1299 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1304 bool check_id(const char *name) {
1305 for(int i = 0; i < strlen(name); i++) {
1306 if(!isalnum(name[i]) && name[i] != '_')
1313 static int cmd_init(int argc, char *argv[]) {
1314 if(!access(tinc_conf, F_OK)) {
1315 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1320 if(isatty(0) && isatty(1)) {
1322 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1324 if(!fgets(buf, sizeof buf, stdin)) {
1325 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1328 int len = rstrip(buf);
1330 fprintf(stderr, "No name given!\n");
1335 fprintf(stderr, "No Name given!\n");
1339 name = strdup(argv[1]);
1341 fprintf(stderr, "No Name given!\n");
1346 if(!check_id(name)) {
1347 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1351 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1352 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1356 if(mkdir(confbase, 0755) && errno != EEXIST) {
1357 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1361 char *hosts_dir = NULL;
1362 xasprintf(&hosts_dir, "%s/hosts", confbase);
1363 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1364 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1368 FILE *f = fopen(tinc_conf, "w");
1370 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1374 fprintf(f, "Name = %s\n", name);
1378 if(!rsa_keygen(2048) || !ecdsa_keygen())
1385 static int cmd_generate_keys(int argc, char *argv[]) {
1386 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1389 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1390 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1393 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1394 return !ecdsa_keygen();
1397 static int cmd_help(int argc, char *argv[]) {
1402 static int cmd_version(int argc, char *argv[]) {
1407 static int cmd_info(int argc, char *argv[]) {
1409 fprintf(stderr, "Invalid number of arguments.\n");
1413 if(!connect_tincd())
1416 return info(fd, argv[1]);
1419 static const char *conffiles[] = {
1430 static int cmd_edit(int argc, char *argv[]) {
1432 fprintf(stderr, "Invalid number of arguments.\n");
1436 char *filename = NULL;
1438 if(strncmp(argv[1], "hosts/", 6)) {
1439 for(int i = 0; conffiles[i]; i++) {
1440 if(!strcmp(argv[1], conffiles[i])) {
1441 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1450 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1451 char *dash = strchr(argv[1], '-');
1454 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1455 fprintf(stderr, "Invalid configuration filename.\n");
1462 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1464 char *editor = "edit";
1468 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1469 int result = system(command);
1473 // Silently try notifying a running tincd of changes.
1477 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1482 static int export(const char *name, FILE *out) {
1484 xasprintf(&filename, "%s/%s", hosts_dir, name);
1485 FILE *in = fopen(filename, "r");
1487 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1491 fprintf(out, "Name = %s\n", name);
1493 while(fgets(buf, sizeof buf, in)) {
1494 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1499 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1507 static int cmd_export(int argc, char *argv[]) {
1508 char *name = get_my_name();
1512 return export(name, stdout);
1515 static int cmd_export_all(int argc, char *argv[]) {
1516 DIR *dir = opendir(hosts_dir);
1518 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1526 while((ent = readdir(dir))) {
1527 if(!check_id(ent->d_name))
1533 printf("#---------------------------------------------------------------#\n");
1535 result |= export(ent->d_name, stdout);
1542 static int cmd_import(int argc, char *argv[]) {
1550 bool firstline = true;
1552 while(fgets(buf, sizeof buf, in)) {
1553 if(sscanf(buf, "Name = %s", name) == 1) {
1554 if(!check_id(name)) {
1555 fprintf(stderr, "Invalid Name in input!\n");
1563 xasprintf(&filename, "%s/%s", hosts_dir, name);
1565 if(!force && !access(filename, F_OK)) {
1566 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1571 out = fopen(filename, "w");
1573 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1580 } else if(firstline) {
1581 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1586 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1590 if(fputs(buf, out) < 0) {
1591 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1601 fprintf(stderr, "Imported %d host configuration files.\n", count);
1604 fprintf(stderr, "No host configuration files imported.\n");
1609 static const struct {
1610 const char *command;
1611 int (*function)(int argc, char *argv[]);
1613 {"start", cmd_start},
1615 {"restart", cmd_restart},
1616 {"reload", cmd_reload},
1618 {"purge", cmd_purge},
1619 {"debug", cmd_debug},
1620 {"retry", cmd_retry},
1621 {"connect", cmd_connect},
1622 {"disconnect", cmd_disconnect},
1627 {"config", cmd_config},
1629 {"generate-keys", cmd_generate_keys},
1630 {"generate-rsa-keys", cmd_generate_rsa_keys},
1631 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1633 {"version", cmd_version},
1636 {"export", cmd_export},
1637 {"export-all", cmd_export_all},
1638 {"import", cmd_import},
1642 int main(int argc, char *argv[]) {
1643 program_name = argv[0];
1645 if(!parse_options(argc, argv))
1660 if(optind >= argc) {
1661 fprintf(stderr, "No command given.\n");
1666 for(int i = 0; commands[i].command; i++) {
1667 if(!strcasecmp(argv[optind], commands[i].command))
1668 return commands[i].function(argc - optind, argv + optind);
1671 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);