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 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
115 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
116 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
117 " start [tincd options] Start tincd.\n"
118 " stop Stop tincd.\n"
119 " restart Restart tincd.\n"
120 " reload Partially reload configuration of running tincd.\n"
121 " pid Show PID of currently running tincd.\n"
122 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
123 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
124 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
125 " dump Dump a list of one of the following things:\n"
126 " nodes - all known nodes in the VPN\n"
127 " edges - all known connections in the VPN\n"
128 " subnets - all known subnets in the VPN\n"
129 " connections - all meta connections with ourself\n"
130 " graph - graph of the VPN in dotty format\n"
131 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
132 " purge Purge unreachable nodes\n"
133 " debug N Set debug level\n"
134 " retry Retry all outgoing connections\n"
135 " disconnect NODE Close meta connection with NODE\n"
137 " top Show real-time statistics\n"
139 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
140 " log [level] Dump log output [up to the specified level]\n"
141 " export Export host configuration of local node to standard output\n"
142 " export-all Export all host configuration files to standard output\n"
143 " import [--force] Import host configuration file(s) from standard input\n"
145 printf("Report bugs to tinc@tinc-vpn.org.\n");
149 static bool parse_options(int argc, char **argv) {
151 int option_index = 0;
153 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
155 case 0: /* long option */
158 case 'c': /* config file */
159 confbase = xstrdup(optarg);
162 case 'n': /* net name given */
163 netname = xstrdup(optarg);
166 case 1: /* show help */
170 case 2: /* show version */
174 case 5: /* open control socket here */
175 pidfilename = xstrdup(optarg);
191 if(!netname && (netname = getenv("NETNAME")))
192 netname = xstrdup(netname);
194 /* netname "." is special: a "top-level name" */
196 if(netname && !strcmp(netname, ".")) {
204 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
210 /* Check stdin and stdout */
211 if(isatty(0) && isatty(1)) {
212 /* Ask for a file and/or directory name. */
213 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
217 if(fgets(buf, sizeof buf, stdin) == NULL) {
218 fprintf(stderr, "Error while reading stdin: %s\n",
223 size_t len = strlen(buf);
232 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
234 if(filename[0] != '/') {
236 /* The directory is a relative path or a filename. */
237 directory = get_current_dir_name();
238 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
242 umask(0077); /* Disallow everything for group and other */
244 /* Open it first to keep the inode busy */
246 r = fopen(filename, mode);
249 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
257 Generate a public/private ECDSA keypair, and ask for a file to store
260 static bool ecdsa_keygen() {
265 fprintf(stderr, "Generating ECDSA keypair:\n");
267 if(!ecdsa_generate(&key)) {
268 fprintf(stderr, "Error during key generation!\n");
271 fprintf(stderr, "Done.\n");
273 xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
274 f = ask_and_open(filename, "private ECDSA key", "a");
280 /* Make it unreadable for others. */
281 fchmod(fileno(f), 0600);
285 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
287 ecdsa_write_pem_private_key(&key, f);
293 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
295 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
297 f = ask_and_open(filename, "public ECDSA key", "a");
303 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
305 char *pubkey = ecdsa_get_base64_public_key(&key);
306 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
316 Generate a public/private RSA keypair, and ask for a file to store
319 static bool rsa_keygen(int bits) {
324 fprintf(stderr, "Generating %d bits keys:\n", bits);
326 if(!rsa_generate(&key, bits, 0x10001)) {
327 fprintf(stderr, "Error during key generation!\n");
330 fprintf(stderr, "Done.\n");
332 xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
333 f = ask_and_open(filename, "private RSA key", "a");
339 /* Make it unreadable for others. */
340 fchmod(fileno(f), 0600);
344 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
346 rsa_write_pem_private_key(&key, f);
352 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
354 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
356 f = ask_and_open(filename, "public RSA key", "a");
362 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
364 rsa_write_pem_public_key(&key, f);
373 Set all files and paths according to netname
375 static void make_names(void) {
378 char installdir[1024] = "";
379 long len = sizeof installdir;
383 xasprintf(&identname, "tinc.%s", netname);
385 identname = xstrdup("tinc");
388 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
389 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
392 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
394 xasprintf(&confbase, "%s", installdir);
398 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
404 confdir = xstrdup(CONFDIR);
407 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
411 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
413 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
416 xasprintf(&confbase, CONFDIR SLASH "tinc");
421 confdir = xstrdup(installdir);
424 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
425 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
428 static char buffer[4096];
429 static size_t blen = 0;
431 bool recvline(int fd, char *line, size_t len) {
432 char *newline = NULL;
434 while(!(newline = memchr(buffer, '\n', blen))) {
435 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
436 if(result == -1 && errno == EINTR)
443 if(newline - buffer >= len)
446 len = newline - buffer;
448 memcpy(line, buffer, len);
450 memmove(buffer, newline + 1, blen - len - 1);
456 static bool recvdata(int fd, char *data, size_t len) {
458 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
459 if(result == -1 && errno == EINTR)
466 memcpy(data, buffer, len);
467 memmove(buffer, buffer + len, blen - len);
473 bool sendline(int fd, char *format, ...) {
474 static char buffer[4096];
479 va_start(ap, format);
480 blen = vsnprintf(buffer, sizeof buffer, format, ap);
483 if(blen < 1 || blen >= sizeof buffer)
490 int result = send(fd, p, blen, 0);
491 if(result == -1 && errno == EINTR)
502 static void pcap(int fd, FILE *out, int snaplen) {
503 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
511 uint32_t tz_accuracy;
518 snaplen ?: sizeof data,
531 fwrite(&header, sizeof header, 1, out);
535 while(recvline(fd, line, sizeof line)) {
537 int n = sscanf(line, "%d %d %d", &code, &req, &len);
538 gettimeofday(&tv, NULL);
539 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
541 if(!recvdata(fd, data, len))
543 packet.tv_sec = tv.tv_sec;
544 packet.tv_usec = tv.tv_usec;
546 packet.origlen = len;
547 fwrite(&packet, sizeof packet, 1, out);
548 fwrite(data, len, 1, out);
553 static void logcontrol(int fd, FILE *out, int level) {
554 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
558 while(recvline(fd, line, sizeof line)) {
560 int n = sscanf(line, "%d %d %d", &code, &req, &len);
561 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
563 if(!recvdata(fd, data, len))
565 fwrite(data, len, 1, out);
572 static bool remove_service(void) {
573 SC_HANDLE manager = NULL;
574 SC_HANDLE service = NULL;
575 SERVICE_STATUS status = {0};
577 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
579 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
583 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
586 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
590 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
591 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
593 fprintf(stderr, "%s service stopped\n", identname);
595 if(!DeleteService(service)) {
596 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
600 fprintf(stderr, "%s service removed\n", identname);
606 static bool connect_tincd() {
610 FILE *f = fopen(pidfilename, "r");
612 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
619 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
620 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
625 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
626 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
631 struct addrinfo hints = {
632 .ai_family = AF_UNSPEC,
633 .ai_socktype = SOCK_STREAM,
634 .ai_protocol = IPPROTO_TCP,
638 struct addrinfo *res = NULL;
640 if(getaddrinfo(host, port, &hints, &res) || !res) {
641 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
645 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
647 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
652 unsigned long arg = 0;
654 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
655 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
659 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
660 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
669 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
670 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
674 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
676 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
677 fprintf(stderr, "Could not fully establish control socket connection\n");
685 static int cmd_start(int argc, char *argv[]) {
691 char *slash = strrchr(argv[0], '/');
694 if ((c = strrchr(argv[0], '\\')) > slash)
699 xasprintf(&c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
705 for(i = j = 1; argv[i]; ++i)
706 if (i != optind && strcmp(argv[i], "--") != 0)
711 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
715 static int cmd_stop(int argc, char *argv[]) {
720 sendline(fd, "%d %d", CONTROL, REQ_STOP);
721 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
722 fprintf(stderr, "Could not stop tinc daemon.\n");
726 if(!remove_service())
732 static int cmd_restart(int argc, char *argv[]) {
733 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
736 static int cmd_reload(int argc, char *argv[]) {
740 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
741 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
742 fprintf(stderr, "Could not reload configuration.\n");
750 static int cmd_dump(int argc, char *argv[]) {
752 fprintf(stderr, "Invalid number of arguments.\n");
760 bool do_graph = false;
762 if(!strcasecmp(argv[1], "nodes"))
763 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
764 else if(!strcasecmp(argv[1], "edges"))
765 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
766 else if(!strcasecmp(argv[1], "subnets"))
767 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
768 else if(!strcasecmp(argv[1], "connections"))
769 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
770 else if(!strcasecmp(argv[1], "graph")) {
771 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
772 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
775 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
781 printf("digraph {\n");
783 while(recvline(fd, line, sizeof line)) {
784 char node1[4096], node2[4096];
785 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
787 if(do_graph && req == REQ_DUMP_NODES)
799 printf("%s\n", line + 5);
801 if(req == REQ_DUMP_NODES)
802 printf(" %s [label = \"%s\"];\n", node1, node1);
804 printf(" %s -> %s;\n", node1, node2);
808 fprintf(stderr, "Error receiving dump.\n");
812 static int cmd_purge(int argc, char *argv[]) {
816 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
817 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
818 fprintf(stderr, "Could not purge old information.\n");
825 static int cmd_debug(int argc, char *argv[]) {
827 fprintf(stderr, "Invalid number of arguments.\n");
834 int debuglevel = atoi(argv[1]);
837 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
838 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
839 fprintf(stderr, "Could not set debug level.\n");
843 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
847 static int cmd_retry(int argc, char *argv[]) {
851 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
852 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
853 fprintf(stderr, "Could not retry outgoing connections.\n");
860 static int cmd_connect(int argc, char *argv[]) {
862 fprintf(stderr, "Invalid number of arguments.\n");
866 if(!check_id(argv[2])) {
867 fprintf(stderr, "Invalid name for node.\n");
874 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
875 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
876 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
883 static int cmd_disconnect(int argc, char *argv[]) {
885 fprintf(stderr, "Invalid number of arguments.\n");
889 if(!check_id(argv[2])) {
890 fprintf(stderr, "Invalid name for node.\n");
897 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
898 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
899 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
906 static int cmd_top(int argc, char *argv[]) {
914 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
919 static int cmd_pcap(int argc, char *argv[]) {
923 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
927 static int cmd_log(int argc, char *argv[]) {
931 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
935 static int cmd_pid(int argc, char *argv[]) {
943 static int rstrip(char *value) {
944 int len = strlen(value);
945 while(len && strchr("\t\r\n ", value[len - 1]))
950 static char *get_my_name() {
951 FILE *f = fopen(tinc_conf, "r");
953 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
959 while(fgets(buf, sizeof buf, f)) {
960 int len = strcspn(buf, "\t =");
962 value += strspn(value, "\t ");
965 value += strspn(value, "\t ");
970 if(strcasecmp(buf, "Name"))
974 return strdup(value);
979 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
983 #define VAR_SERVER 1 /* Should be in tinc.conf */
984 #define VAR_HOST 2 /* Can be in host config file */
985 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
986 #define VAR_OBSOLETE 8 /* Should not be used anymore */
991 } const variables[] = {
992 /* Server configuration */
993 {"AddressFamily", VAR_SERVER},
994 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
995 {"BindToInterface", VAR_SERVER},
996 {"Broadcast", VAR_SERVER},
997 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
998 {"DecrementTTL", VAR_SERVER},
999 {"Device", VAR_SERVER},
1000 {"DeviceType", VAR_SERVER},
1001 {"DirectOnly", VAR_SERVER},
1002 {"ECDSAPrivateKeyFile", VAR_SERVER},
1003 {"ExperimentalProtocol", VAR_SERVER},
1004 {"Forwarding", VAR_SERVER},
1005 {"GraphDumpFile", VAR_SERVER},
1006 {"Hostnames", VAR_SERVER},
1007 {"IffOneQueue", VAR_SERVER},
1008 {"Interface", VAR_SERVER},
1009 {"KeyExpire", VAR_SERVER},
1010 {"LocalDiscovery", VAR_SERVER},
1011 {"MACExpire", VAR_SERVER},
1012 {"MaxTimeout", VAR_SERVER},
1013 {"Mode", VAR_SERVER},
1014 {"Name", VAR_SERVER},
1015 {"PingInterval", VAR_SERVER},
1016 {"PingTimeout", VAR_SERVER},
1017 {"PriorityInheritance", VAR_SERVER},
1018 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1019 {"PrivateKeyFile", VAR_SERVER},
1020 {"ProcessPriority", VAR_SERVER},
1021 {"ReplayWindow", VAR_SERVER},
1022 {"StrictSubnets", VAR_SERVER},
1023 {"TunnelServer", VAR_SERVER},
1024 {"UDPRcvBuf", VAR_SERVER},
1025 {"UDPSndBuf", VAR_SERVER},
1026 /* Host configuration */
1027 {"Address", VAR_HOST | VAR_MULTIPLE},
1028 {"Cipher", VAR_SERVER | VAR_HOST},
1029 {"ClampMSS", VAR_SERVER | VAR_HOST},
1030 {"Compression", VAR_SERVER | VAR_HOST},
1031 {"Digest", VAR_SERVER | VAR_HOST},
1032 {"IndirectData", VAR_SERVER | VAR_HOST},
1033 {"MACLength", VAR_SERVER | VAR_HOST},
1034 {"PMTU", VAR_SERVER | VAR_HOST},
1035 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1037 {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1038 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1039 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1040 {"TCPOnly", VAR_SERVER | VAR_HOST},
1044 static int cmd_config(int argc, char *argv[]) {
1046 fprintf(stderr, "Invalid number of arguments.\n");
1051 if(!strcasecmp(argv[1], "add")) {
1052 argv++, argc--, action = 1;
1053 } else if(!strcasecmp(argv[1], "del")) {
1054 argv++, argc--, action = -1;
1055 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1056 argv++, argc--, action = 0;
1060 fprintf(stderr, "Invalid number of arguments.\n");
1064 // Concatenate the rest of the command line
1065 strncpy(line, argv[1], sizeof line - 1);
1066 for(int i = 2; i < argc; i++) {
1067 strncat(line, " ", sizeof line - 1 - strlen(line));
1068 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1071 // Liberal parsing into node name, variable name and value.
1077 len = strcspn(line, "\t =");
1079 value += strspn(value, "\t ");
1082 value += strspn(value, "\t ");
1085 variable = strchr(line, '.');
1094 fprintf(stderr, "No variable given.\n");
1098 if(action >= 0 && !*value) {
1099 fprintf(stderr, "No value for variable given.\n");
1103 /* Some simple checks. */
1106 for(int i = 0; variables[i].name; i++) {
1107 if(strcasecmp(variables[i].name, variable))
1111 variable = (char *)variables[i].name;
1113 /* Discourage use of obsolete variables. */
1115 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1117 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1119 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1124 /* Don't put server variables in host config files */
1126 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1128 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1130 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1135 /* Should this go into our own host config file? */
1137 if(!node && !(variables[i].type & VAR_SERVER)) {
1138 node = get_my_name();
1146 if(node && !check_id(node)) {
1147 fprintf(stderr, "Invalid name for node.\n");
1151 if(!found && action >= 0) {
1153 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1155 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1160 // Open the right configuration file.
1163 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1165 filename = tinc_conf;
1167 FILE *f = fopen(filename, "r");
1169 if(action < 0 || errno != ENOENT) {
1170 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1174 // If it doesn't exist, create it.
1175 f = fopen(filename, "a+");
1177 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1180 fprintf(stderr, "Created configuration file %s.\n", filename);
1185 xasprintf(&tmpfile, "%s.config.tmp", filename);
1186 FILE *tf = fopen(tmpfile, "w");
1188 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1192 // Copy the file, making modifications on the fly.
1196 bool removed = false;
1198 while(fgets(buf1, sizeof buf1, f)) {
1199 buf1[sizeof buf1 - 1] = 0;
1200 strncpy(buf2, buf1, sizeof buf2);
1202 // Parse line in a simple way
1206 len = strcspn(buf2, "\t =");
1207 bvalue = buf2 + len;
1208 bvalue += strspn(bvalue, "\t ");
1209 if(*bvalue == '=') {
1211 bvalue += strspn(bvalue, "\t ");
1217 if(!strcasecmp(buf2, variable)) {
1220 if(!*value || !strcasecmp(bvalue, value)) {
1225 } else if(action == 0) {
1226 // Already set? Delete the rest...
1229 // Otherwise, replace.
1230 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1231 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1239 // Copy original line...
1240 if(fputs(buf1, tf) < 0) {
1241 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1245 // Add newline if it is missing...
1246 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1247 if(fputc('\n', tf) < 0) {
1248 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1254 // Make sure we read everything...
1255 if(ferror(f) || !feof(f)) {
1256 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1261 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1265 // Add new variable if necessary.
1266 if(action > 0 || (action == 0 && !set)) {
1267 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1268 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1273 // Make sure we wrote everything...
1275 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1279 // Could we find what we had to remove?
1280 if(action < 0 && !removed) {
1282 fprintf(stderr, "No configuration variables deleted.\n");
1286 // Replace the configuration file with the new one
1288 if(remove(filename)) {
1289 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1293 if(rename(tmpfile, filename)) {
1294 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1298 // Silently try notifying a running tincd of changes.
1302 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1307 bool check_id(const char *name) {
1308 for(int i = 0; i < strlen(name); i++) {
1309 if(!isalnum(name[i]) && name[i] != '_')
1316 static int cmd_init(int argc, char *argv[]) {
1317 if(!access(tinc_conf, F_OK)) {
1318 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1323 if(isatty(0) && isatty(1)) {
1325 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1327 if(!fgets(buf, sizeof buf, stdin)) {
1328 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1331 int len = rstrip(buf);
1333 fprintf(stderr, "No name given!\n");
1338 fprintf(stderr, "No Name given!\n");
1342 name = strdup(argv[1]);
1344 fprintf(stderr, "No Name given!\n");
1349 if(!check_id(name)) {
1350 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1354 if(mkdir(confdir, 0755) && errno != EEXIST) {
1355 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1359 if(mkdir(confbase, 0755) && errno != EEXIST) {
1360 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1364 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1365 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1369 FILE *f = fopen(tinc_conf, "w");
1371 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1375 fprintf(f, "Name = %s\n", name);
1379 if(!rsa_keygen(2048) || !ecdsa_keygen())
1384 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1385 if(access(filename, F_OK)) {
1386 FILE *f = fopen(filename, "w");
1388 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1391 fchmod(fileno(f), 0755);
1392 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");
1401 static int cmd_generate_keys(int argc, char *argv[]) {
1402 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1405 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1406 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1409 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1410 return !ecdsa_keygen();
1413 static int cmd_help(int argc, char *argv[]) {
1418 static int cmd_version(int argc, char *argv[]) {
1423 static int cmd_info(int argc, char *argv[]) {
1425 fprintf(stderr, "Invalid number of arguments.\n");
1429 if(!connect_tincd())
1432 return info(fd, argv[1]);
1435 static const char *conffiles[] = {
1446 static int cmd_edit(int argc, char *argv[]) {
1448 fprintf(stderr, "Invalid number of arguments.\n");
1452 char *filename = NULL;
1454 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1455 for(int i = 0; conffiles[i]; i++) {
1456 if(!strcmp(argv[1], conffiles[i])) {
1457 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1466 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1467 char *dash = strchr(argv[1], '-');
1470 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1471 fprintf(stderr, "Invalid configuration filename.\n");
1479 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1481 xasprintf(&command, "edit \"%s\"", filename);
1483 int result = system(command);
1487 // Silently try notifying a running tincd of changes.
1491 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1496 static int export(const char *name, FILE *out) {
1498 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1499 FILE *in = fopen(filename, "r");
1501 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1505 fprintf(out, "Name = %s\n", name);
1507 while(fgets(buf, sizeof buf, in)) {
1508 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1513 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1521 static int cmd_export(int argc, char *argv[]) {
1522 char *name = get_my_name();
1526 return export(name, stdout);
1529 static int cmd_export_all(int argc, char *argv[]) {
1530 DIR *dir = opendir(hosts_dir);
1532 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1540 while((ent = readdir(dir))) {
1541 if(!check_id(ent->d_name))
1547 printf("#---------------------------------------------------------------#\n");
1549 result |= export(ent->d_name, stdout);
1556 static int cmd_import(int argc, char *argv[]) {
1564 bool firstline = true;
1566 while(fgets(buf, sizeof buf, in)) {
1567 if(sscanf(buf, "Name = %s", name) == 1) {
1568 if(!check_id(name)) {
1569 fprintf(stderr, "Invalid Name in input!\n");
1577 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1579 if(!force && !access(filename, F_OK)) {
1580 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1585 out = fopen(filename, "w");
1587 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1594 } else if(firstline) {
1595 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1600 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1604 if(fputs(buf, out) < 0) {
1605 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1615 fprintf(stderr, "Imported %d host configuration files.\n", count);
1618 fprintf(stderr, "No host configuration files imported.\n");
1623 static const struct {
1624 const char *command;
1625 int (*function)(int argc, char *argv[]);
1627 {"start", cmd_start},
1629 {"restart", cmd_restart},
1630 {"reload", cmd_reload},
1632 {"purge", cmd_purge},
1633 {"debug", cmd_debug},
1634 {"retry", cmd_retry},
1635 {"connect", cmd_connect},
1636 {"disconnect", cmd_disconnect},
1641 {"config", cmd_config},
1643 {"generate-keys", cmd_generate_keys},
1644 {"generate-rsa-keys", cmd_generate_rsa_keys},
1645 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1647 {"version", cmd_version},
1650 {"export", cmd_export},
1651 {"export-all", cmd_export_all},
1652 {"import", cmd_import},
1656 int main(int argc, char *argv[]) {
1657 program_name = argv[0];
1659 if(!parse_options(argc, argv))
1674 if(optind >= argc) {
1675 fprintf(stderr, "No command given.\n");
1680 for(int i = 0; commands[i].command; i++) {
1681 if(!strcasecmp(argv[optind], commands[i].command))
1682 return commands[i].function(argc - optind, argv + optind);
1685 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);