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 *confdir = NULL;
51 static char controlcookie[1024];
53 char *confbase = NULL;
54 static char *tinc_conf = NULL;
55 static char *hosts_dir = NULL;
57 // Horrible global variables...
60 static char line[4096];
64 static bool force = false;
67 static struct WSAData wsa_state;
70 static struct option const long_options[] = {
71 {"config", required_argument, NULL, 'c'},
72 {"debug", optional_argument, NULL, 0},
73 {"no-detach", no_argument, NULL, 0},
74 {"mlock", no_argument, NULL, 0},
75 {"net", required_argument, NULL, 'n'},
76 {"help", no_argument, NULL, 1},
77 {"version", no_argument, NULL, 2},
78 {"pidfile", required_argument, NULL, 5},
79 {"logfile", required_argument, NULL, 0},
80 {"bypass-security", no_argument, NULL, 0},
81 {"chroot", no_argument, NULL, 0},
82 {"user", required_argument, NULL, 0},
83 {"option", required_argument, NULL, 0},
84 {"force", no_argument, NULL, 6},
88 static void version(void) {
89 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
90 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
91 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
92 "See the AUTHORS file for a complete list.\n\n"
93 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
94 "and you are welcome to redistribute it under certain conditions;\n"
95 "see the file COPYING for details.\n");
98 static void usage(bool status) {
100 fprintf(stderr, "Try `%s --help\' for more information.\n",
103 printf("Usage: %s [options] command\n\n", program_name);
104 printf("Valid options are:\n"
105 " -c, --config=DIR Read configuration options from DIR.\n"
106 " -n, --net=NETNAME Connect to net NETNAME.\n"
107 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
108 " --help Display this help and exit.\n"
109 " --version Output version information and exit.\n"
111 "Valid commands are:\n"
112 " init [name] Create initial configuration files.\n"
113 " config Change configuration:\n"
114 " [get] VARIABLE - print current value of VARIABLE\n"
115 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
116 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
117 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
118 " start [tincd options] Start tincd.\n"
119 " stop Stop tincd.\n"
120 " restart Restart tincd.\n"
121 " reload Partially reload configuration of running tincd.\n"
122 " pid Show PID of currently running tincd.\n"
123 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
124 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
125 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
126 " dump Dump a list of one of the following things:\n"
127 " nodes - all known nodes in the VPN\n"
128 " edges - all known connections in the VPN\n"
129 " subnets - all known subnets in the VPN\n"
130 " connections - all meta connections with ourself\n"
131 " graph - graph of the VPN in dotty format\n"
132 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
133 " purge Purge unreachable nodes\n"
134 " debug N Set debug level\n"
135 " retry Retry all outgoing connections\n"
136 " disconnect NODE Close meta connection with NODE\n"
138 " top Show real-time statistics\n"
140 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
141 " log [level] Dump log output [up to the specified level]\n"
142 " export Export host configuration of local node to standard output\n"
143 " export-all Export all host configuration files to standard output\n"
144 " import [--force] Import host configuration file(s) from standard input\n"
146 printf("Report bugs to tinc@tinc-vpn.org.\n");
150 static bool parse_options(int argc, char **argv) {
152 int option_index = 0;
154 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
156 case 0: /* long option */
159 case 'c': /* config file */
160 confbase = xstrdup(optarg);
163 case 'n': /* net name given */
164 netname = xstrdup(optarg);
167 case 1: /* show help */
171 case 2: /* show version */
175 case 5: /* open control socket here */
176 pidfilename = xstrdup(optarg);
192 if(!netname && (netname = getenv("NETNAME")))
193 netname = xstrdup(netname);
195 /* netname "." is special: a "top-level name" */
197 if(netname && !strcmp(netname, ".")) {
205 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
211 /* Check stdin and stdout */
212 if(isatty(0) && isatty(1)) {
213 /* Ask for a file and/or directory name. */
214 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
218 if(fgets(buf, sizeof buf, stdin) == NULL) {
219 fprintf(stderr, "Error while reading stdin: %s\n",
224 size_t len = strlen(buf);
233 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
235 if(filename[0] != '/') {
237 /* The directory is a relative path or a filename. */
238 directory = get_current_dir_name();
239 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
243 umask(0077); /* Disallow everything for group and other */
245 /* Open it first to keep the inode busy */
247 r = fopen(filename, mode);
250 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
258 Generate a public/private ECDSA keypair, and ask for a file to store
261 static bool ecdsa_keygen() {
266 fprintf(stderr, "Generating ECDSA keypair:\n");
268 if(!ecdsa_generate(&key)) {
269 fprintf(stderr, "Error during key generation!\n");
272 fprintf(stderr, "Done.\n");
274 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
275 f = ask_and_open(filename, "private ECDSA key", "a");
281 /* Make it unreadable for others. */
282 fchmod(fileno(f), 0600);
286 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
288 ecdsa_write_pem_private_key(&key, f);
294 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
296 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
298 f = ask_and_open(filename, "public ECDSA key", "a");
304 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
306 char *pubkey = ecdsa_get_base64_public_key(&key);
307 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
317 Generate a public/private RSA keypair, and ask for a file to store
320 static bool rsa_keygen(int bits) {
325 fprintf(stderr, "Generating %d bits keys:\n", bits);
327 if(!rsa_generate(&key, bits, 0x10001)) {
328 fprintf(stderr, "Error during key generation!\n");
331 fprintf(stderr, "Done.\n");
333 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
334 f = ask_and_open(filename, "private RSA key", "a");
340 /* Make it unreadable for others. */
341 fchmod(fileno(f), 0600);
345 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
347 rsa_write_pem_private_key(&key, f);
353 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
355 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
357 f = ask_and_open(filename, "public RSA key", "a");
363 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
365 rsa_write_pem_public_key(&key, f);
374 Set all files and paths according to netname
376 static void make_names(void) {
379 char installdir[1024] = "";
380 long len = sizeof installdir;
384 xasprintf(&identname, "tinc.%s", netname);
386 identname = xstrdup("tinc");
389 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
390 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
393 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
395 xasprintf(&confbase, "%s", installdir);
399 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
405 confdir = xstrdup(CONFDIR);
408 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
412 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
414 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
417 xasprintf(&confbase, CONFDIR SLASH "tinc");
422 confdir = xstrdup(installdir);
425 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
426 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
429 static char buffer[4096];
430 static size_t blen = 0;
432 bool recvline(int fd, char *line, size_t len) {
433 char *newline = NULL;
435 while(!(newline = memchr(buffer, '\n', blen))) {
436 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
437 if(result == -1 && errno == EINTR)
444 if(newline - buffer >= len)
447 len = newline - buffer;
449 memcpy(line, buffer, len);
451 memmove(buffer, newline + 1, blen - len - 1);
457 static bool recvdata(int fd, char *data, size_t len) {
459 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
460 if(result == -1 && errno == EINTR)
467 memcpy(data, buffer, len);
468 memmove(buffer, buffer + len, blen - len);
474 bool sendline(int fd, char *format, ...) {
475 static char buffer[4096];
480 va_start(ap, format);
481 blen = vsnprintf(buffer, sizeof buffer, format, ap);
484 if(blen < 1 || blen >= sizeof buffer)
491 int result = send(fd, p, blen, 0);
492 if(result == -1 && errno == EINTR)
503 static void pcap(int fd, FILE *out, int snaplen) {
504 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
512 uint32_t tz_accuracy;
519 snaplen ?: sizeof data,
532 fwrite(&header, sizeof header, 1, out);
536 while(recvline(fd, line, sizeof line)) {
538 int n = sscanf(line, "%d %d %d", &code, &req, &len);
539 gettimeofday(&tv, NULL);
540 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
542 if(!recvdata(fd, data, len))
544 packet.tv_sec = tv.tv_sec;
545 packet.tv_usec = tv.tv_usec;
547 packet.origlen = len;
548 fwrite(&packet, sizeof packet, 1, out);
549 fwrite(data, len, 1, out);
554 static void logcontrol(int fd, FILE *out, int level) {
555 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
559 while(recvline(fd, line, sizeof line)) {
561 int n = sscanf(line, "%d %d %d", &code, &req, &len);
562 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
564 if(!recvdata(fd, data, len))
566 fwrite(data, len, 1, out);
573 static bool remove_service(void) {
574 SC_HANDLE manager = NULL;
575 SC_HANDLE service = NULL;
576 SERVICE_STATUS status = {0};
578 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
580 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
584 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
587 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
591 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
592 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
594 fprintf(stderr, "%s service stopped\n", identname);
596 if(!DeleteService(service)) {
597 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
601 fprintf(stderr, "%s service removed\n", identname);
607 static bool connect_tincd() {
611 FILE *f = fopen(pidfilename, "r");
613 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
620 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
621 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
626 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
627 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
632 struct addrinfo hints = {
633 .ai_family = AF_UNSPEC,
634 .ai_socktype = SOCK_STREAM,
635 .ai_protocol = IPPROTO_TCP,
639 struct addrinfo *res = NULL;
641 if(getaddrinfo(host, port, &hints, &res) || !res) {
642 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
646 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
648 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
653 unsigned long arg = 0;
655 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
656 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
660 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
661 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
670 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
671 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
675 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
677 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
678 fprintf(stderr, "Could not fully establish control socket connection\n");
686 static int cmd_start(int argc, char *argv[]) {
692 char *slash = strrchr(argv[0], '/');
695 if ((c = strrchr(argv[0], '\\')) > slash)
700 xasprintf(&c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
706 for(i = j = 1; argv[i]; ++i)
707 if (i != optind && strcmp(argv[i], "--") != 0)
712 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
716 static int cmd_stop(int argc, char *argv[]) {
718 if(!connect_tincd()) {
720 if(kill(pid, SIGTERM))
722 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
729 sendline(fd, "%d %d", CONTROL, REQ_STOP);
730 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
731 fprintf(stderr, "Could not stop tinc daemon.\n");
735 if(!remove_service())
741 static int cmd_restart(int argc, char *argv[]) {
742 cmd_stop(argc, argv);
743 return cmd_start(argc, argv);
746 static int cmd_reload(int argc, char *argv[]) {
750 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
751 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
752 fprintf(stderr, "Could not reload configuration.\n");
760 static int cmd_dump(int argc, char *argv[]) {
762 fprintf(stderr, "Invalid number of arguments.\n");
770 bool do_graph = false;
772 if(!strcasecmp(argv[1], "nodes"))
773 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
774 else if(!strcasecmp(argv[1], "edges"))
775 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
776 else if(!strcasecmp(argv[1], "subnets"))
777 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
778 else if(!strcasecmp(argv[1], "connections"))
779 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
780 else if(!strcasecmp(argv[1], "graph")) {
781 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
782 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
785 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
791 printf("digraph {\n");
793 while(recvline(fd, line, sizeof line)) {
794 char node1[4096], node2[4096];
795 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
797 if(do_graph && req == REQ_DUMP_NODES)
809 printf("%s\n", line + 5);
811 if(req == REQ_DUMP_NODES)
812 printf(" %s [label = \"%s\"];\n", node1, node1);
814 printf(" %s -> %s;\n", node1, node2);
818 fprintf(stderr, "Error receiving dump.\n");
822 static int cmd_purge(int argc, char *argv[]) {
826 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
827 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
828 fprintf(stderr, "Could not purge old information.\n");
835 static int cmd_debug(int argc, char *argv[]) {
837 fprintf(stderr, "Invalid number of arguments.\n");
844 int debuglevel = atoi(argv[1]);
847 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
848 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
849 fprintf(stderr, "Could not set debug level.\n");
853 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
857 static int cmd_retry(int argc, char *argv[]) {
861 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
862 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
863 fprintf(stderr, "Could not retry outgoing connections.\n");
870 static int cmd_connect(int argc, char *argv[]) {
872 fprintf(stderr, "Invalid number of arguments.\n");
876 if(!check_id(argv[2])) {
877 fprintf(stderr, "Invalid name for node.\n");
884 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
885 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
886 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
893 static int cmd_disconnect(int argc, char *argv[]) {
895 fprintf(stderr, "Invalid number of arguments.\n");
899 if(!check_id(argv[2])) {
900 fprintf(stderr, "Invalid name for node.\n");
907 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
908 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
909 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
916 static int cmd_top(int argc, char *argv[]) {
924 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
929 static int cmd_pcap(int argc, char *argv[]) {
933 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
937 static int cmd_log(int argc, char *argv[]) {
941 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
945 static int cmd_pid(int argc, char *argv[]) {
946 if(!connect_tincd() && !pid)
953 static int rstrip(char *value) {
954 int len = strlen(value);
955 while(len && strchr("\t\r\n ", value[len - 1]))
960 static char *get_my_name() {
961 FILE *f = fopen(tinc_conf, "r");
963 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
969 while(fgets(buf, sizeof buf, f)) {
970 int len = strcspn(buf, "\t =");
972 value += strspn(value, "\t ");
975 value += strspn(value, "\t ");
980 if(strcasecmp(buf, "Name"))
984 return strdup(value);
989 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
993 #define VAR_SERVER 1 /* Should be in tinc.conf */
994 #define VAR_HOST 2 /* Can be in host config file */
995 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
996 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1001 } const variables[] = {
1002 /* Server configuration */
1003 {"AddressFamily", VAR_SERVER},
1004 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1005 {"BindToInterface", VAR_SERVER},
1006 {"Broadcast", VAR_SERVER},
1007 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1008 {"DecrementTTL", VAR_SERVER},
1009 {"Device", VAR_SERVER},
1010 {"DeviceType", VAR_SERVER},
1011 {"DirectOnly", VAR_SERVER},
1012 {"ECDSAPrivateKeyFile", VAR_SERVER},
1013 {"ExperimentalProtocol", VAR_SERVER},
1014 {"Forwarding", VAR_SERVER},
1015 {"GraphDumpFile", VAR_SERVER},
1016 {"Hostnames", VAR_SERVER},
1017 {"IffOneQueue", VAR_SERVER},
1018 {"Interface", VAR_SERVER},
1019 {"KeyExpire", VAR_SERVER},
1020 {"LocalDiscovery", VAR_SERVER},
1021 {"MACExpire", VAR_SERVER},
1022 {"MaxTimeout", VAR_SERVER},
1023 {"Mode", VAR_SERVER},
1024 {"Name", VAR_SERVER},
1025 {"PingInterval", VAR_SERVER},
1026 {"PingTimeout", VAR_SERVER},
1027 {"PriorityInheritance", VAR_SERVER},
1028 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1029 {"PrivateKeyFile", VAR_SERVER},
1030 {"ProcessPriority", VAR_SERVER},
1031 {"ReplayWindow", VAR_SERVER},
1032 {"StrictSubnets", VAR_SERVER},
1033 {"TunnelServer", VAR_SERVER},
1034 {"UDPRcvBuf", VAR_SERVER},
1035 {"UDPSndBuf", VAR_SERVER},
1036 /* Host configuration */
1037 {"Address", VAR_HOST | VAR_MULTIPLE},
1038 {"Cipher", VAR_SERVER | VAR_HOST},
1039 {"ClampMSS", VAR_SERVER | VAR_HOST},
1040 {"Compression", VAR_SERVER | VAR_HOST},
1041 {"Digest", VAR_SERVER | VAR_HOST},
1042 {"IndirectData", VAR_SERVER | VAR_HOST},
1043 {"MACLength", VAR_SERVER | VAR_HOST},
1044 {"PMTU", VAR_SERVER | VAR_HOST},
1045 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1047 {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1048 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1049 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1050 {"TCPOnly", VAR_SERVER | VAR_HOST},
1054 static int cmd_config(int argc, char *argv[]) {
1056 fprintf(stderr, "Invalid number of arguments.\n");
1061 if(!strcasecmp(argv[1], "get")) {
1063 } else if(!strcasecmp(argv[1], "add")) {
1064 argv++, argc--, action = 1;
1065 } else if(!strcasecmp(argv[1], "del")) {
1066 argv++, argc--, action = -1;
1067 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1068 argv++, argc--, action = 0;
1072 fprintf(stderr, "Invalid number of arguments.\n");
1076 // Concatenate the rest of the command line
1077 strncpy(line, argv[1], sizeof line - 1);
1078 for(int i = 2; i < argc; i++) {
1079 strncat(line, " ", sizeof line - 1 - strlen(line));
1080 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1083 // Liberal parsing into node name, variable name and value.
1089 len = strcspn(line, "\t =");
1091 value += strspn(value, "\t ");
1094 value += strspn(value, "\t ");
1097 variable = strchr(line, '.');
1106 fprintf(stderr, "No variable given.\n");
1110 if(action >= 0 && !*value) {
1111 fprintf(stderr, "No value for variable given.\n");
1115 if(action < -1 && *value)
1118 /* Some simple checks. */
1121 for(int i = 0; variables[i].name; i++) {
1122 if(strcasecmp(variables[i].name, variable))
1126 variable = (char *)variables[i].name;
1128 /* Discourage use of obsolete variables. */
1130 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1132 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1134 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1139 /* Don't put server variables in host config files */
1141 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1143 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1145 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1150 /* Should this go into our own host config file? */
1152 if(!node && !(variables[i].type & VAR_SERVER)) {
1153 node = get_my_name();
1161 if(node && !check_id(node)) {
1162 fprintf(stderr, "Invalid name for node.\n");
1167 if(force || action < 0) {
1168 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1170 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1175 // Open the right configuration file.
1178 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1180 filename = tinc_conf;
1182 FILE *f = fopen(filename, "r");
1184 if(action < 0 || errno != ENOENT) {
1185 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1189 // If it doesn't exist, create it.
1190 f = fopen(filename, "a+");
1192 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1195 fprintf(stderr, "Created configuration file %s.\n", filename);
1199 char *tmpfile = NULL;
1203 xasprintf(&tmpfile, "%s.config.tmp", filename);
1204 tf = fopen(tmpfile, "w");
1206 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1211 // Copy the file, making modifications on the fly, unless we are just getting a value.
1215 bool removed = false;
1218 while(fgets(buf1, sizeof buf1, f)) {
1219 buf1[sizeof buf1 - 1] = 0;
1220 strncpy(buf2, buf1, sizeof buf2);
1222 // Parse line in a simple way
1226 len = strcspn(buf2, "\t =");
1227 bvalue = buf2 + len;
1228 bvalue += strspn(bvalue, "\t ");
1229 if(*bvalue == '=') {
1231 bvalue += strspn(bvalue, "\t ");
1237 if(!strcasecmp(buf2, variable)) {
1241 printf("%s\n", bvalue);
1243 } else if(action == -1) {
1244 if(!*value || !strcasecmp(bvalue, value)) {
1249 } else if(action == 0) {
1250 // Already set? Delete the rest...
1253 // Otherwise, replace.
1254 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1255 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1264 // Copy original line...
1265 if(fputs(buf1, tf) < 0) {
1266 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1270 // Add newline if it is missing...
1271 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1272 if(fputc('\n', tf) < 0) {
1273 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1280 // Make sure we read everything...
1281 if(ferror(f) || !feof(f)) {
1282 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1287 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1291 // Add new variable if necessary.
1292 if(action > 0 || (action == 0 && !set)) {
1293 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1294 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1301 fprintf(stderr, "No matching configuration variables found.\n");
1305 // Make sure we wrote everything...
1307 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1311 // Could we find what we had to remove?
1312 if(action < 0 && !removed) {
1314 fprintf(stderr, "No configuration variables deleted.\n");
1318 // Replace the configuration file with the new one
1320 if(remove(filename)) {
1321 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1325 if(rename(tmpfile, filename)) {
1326 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1330 // Silently try notifying a running tincd of changes.
1334 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1339 bool check_id(const char *name) {
1340 for(int i = 0; i < strlen(name); i++) {
1341 if(!isalnum(name[i]) && name[i] != '_')
1348 static int cmd_init(int argc, char *argv[]) {
1349 if(!access(tinc_conf, F_OK)) {
1350 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1355 if(isatty(0) && isatty(1)) {
1357 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1359 if(!fgets(buf, sizeof buf, stdin)) {
1360 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1363 int len = rstrip(buf);
1365 fprintf(stderr, "No name given!\n");
1370 fprintf(stderr, "No Name given!\n");
1374 name = strdup(argv[1]);
1376 fprintf(stderr, "No Name given!\n");
1381 if(!check_id(name)) {
1382 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1386 if(mkdir(confdir, 0755) && errno != EEXIST) {
1387 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1391 if(mkdir(confbase, 0755) && errno != EEXIST) {
1392 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1396 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1397 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1401 FILE *f = fopen(tinc_conf, "w");
1403 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1407 fprintf(f, "Name = %s\n", name);
1411 if(!rsa_keygen(2048) || !ecdsa_keygen())
1416 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1417 if(access(filename, F_OK)) {
1418 FILE *f = fopen(filename, "w");
1420 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1423 fchmod(fileno(f), 0755);
1424 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");
1433 static int cmd_generate_keys(int argc, char *argv[]) {
1434 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1437 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1438 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1441 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1442 return !ecdsa_keygen();
1445 static int cmd_help(int argc, char *argv[]) {
1450 static int cmd_version(int argc, char *argv[]) {
1455 static int cmd_info(int argc, char *argv[]) {
1457 fprintf(stderr, "Invalid number of arguments.\n");
1461 if(!connect_tincd())
1464 return info(fd, argv[1]);
1467 static const char *conffiles[] = {
1478 static int cmd_edit(int argc, char *argv[]) {
1480 fprintf(stderr, "Invalid number of arguments.\n");
1484 char *filename = NULL;
1486 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1487 for(int i = 0; conffiles[i]; i++) {
1488 if(!strcmp(argv[1], conffiles[i])) {
1489 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1498 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1499 char *dash = strchr(argv[1], '-');
1502 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1503 fprintf(stderr, "Invalid configuration filename.\n");
1511 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1513 xasprintf(&command, "edit \"%s\"", filename);
1515 int result = system(command);
1519 // Silently try notifying a running tincd of changes.
1523 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1528 static int export(const char *name, FILE *out) {
1530 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1531 FILE *in = fopen(filename, "r");
1533 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1537 fprintf(out, "Name = %s\n", name);
1539 while(fgets(buf, sizeof buf, in)) {
1540 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1545 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1553 static int cmd_export(int argc, char *argv[]) {
1554 char *name = get_my_name();
1558 return export(name, stdout);
1561 static int cmd_export_all(int argc, char *argv[]) {
1562 DIR *dir = opendir(hosts_dir);
1564 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1572 while((ent = readdir(dir))) {
1573 if(!check_id(ent->d_name))
1579 printf("#---------------------------------------------------------------#\n");
1581 result |= export(ent->d_name, stdout);
1588 static int cmd_import(int argc, char *argv[]) {
1596 bool firstline = true;
1598 while(fgets(buf, sizeof buf, in)) {
1599 if(sscanf(buf, "Name = %s", name) == 1) {
1600 if(!check_id(name)) {
1601 fprintf(stderr, "Invalid Name in input!\n");
1609 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1611 if(!force && !access(filename, F_OK)) {
1612 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1617 out = fopen(filename, "w");
1619 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1626 } else if(firstline) {
1627 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1632 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1636 if(fputs(buf, out) < 0) {
1637 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1647 fprintf(stderr, "Imported %d host configuration files.\n", count);
1650 fprintf(stderr, "No host configuration files imported.\n");
1655 static const struct {
1656 const char *command;
1657 int (*function)(int argc, char *argv[]);
1659 {"start", cmd_start},
1661 {"restart", cmd_restart},
1662 {"reload", cmd_reload},
1664 {"purge", cmd_purge},
1665 {"debug", cmd_debug},
1666 {"retry", cmd_retry},
1667 {"connect", cmd_connect},
1668 {"disconnect", cmd_disconnect},
1673 {"config", cmd_config},
1675 {"generate-keys", cmd_generate_keys},
1676 {"generate-rsa-keys", cmd_generate_rsa_keys},
1677 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1679 {"version", cmd_version},
1682 {"export", cmd_export},
1683 {"export-all", cmd_export_all},
1684 {"import", cmd_import},
1688 int main(int argc, char *argv[]) {
1689 program_name = argv[0];
1691 if(!parse_options(argc, argv))
1706 if(optind >= argc) {
1707 fprintf(stderr, "No command given.\n");
1712 for(int i = 0; commands[i].command; i++) {
1713 if(!strcasecmp(argv[optind], commands[i].command))
1714 return commands[i].function(argc - optind, argv + optind);
1717 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);