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[]) {
717 if(!connect_tincd()) {
719 if(kill(pid, SIGTERM))
721 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
728 sendline(fd, "%d %d", CONTROL, REQ_STOP);
729 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
730 fprintf(stderr, "Could not stop tinc daemon.\n");
734 if(!remove_service())
740 static int cmd_restart(int argc, char *argv[]) {
741 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
744 static int cmd_reload(int argc, char *argv[]) {
748 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
749 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
750 fprintf(stderr, "Could not reload configuration.\n");
758 static int cmd_dump(int argc, char *argv[]) {
760 fprintf(stderr, "Invalid number of arguments.\n");
768 bool do_graph = false;
770 if(!strcasecmp(argv[1], "nodes"))
771 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
772 else if(!strcasecmp(argv[1], "edges"))
773 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
774 else if(!strcasecmp(argv[1], "subnets"))
775 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
776 else if(!strcasecmp(argv[1], "connections"))
777 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
778 else if(!strcasecmp(argv[1], "graph")) {
779 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
780 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
783 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
789 printf("digraph {\n");
791 while(recvline(fd, line, sizeof line)) {
792 char node1[4096], node2[4096];
793 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
795 if(do_graph && req == REQ_DUMP_NODES)
807 printf("%s\n", line + 5);
809 if(req == REQ_DUMP_NODES)
810 printf(" %s [label = \"%s\"];\n", node1, node1);
812 printf(" %s -> %s;\n", node1, node2);
816 fprintf(stderr, "Error receiving dump.\n");
820 static int cmd_purge(int argc, char *argv[]) {
824 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
825 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
826 fprintf(stderr, "Could not purge old information.\n");
833 static int cmd_debug(int argc, char *argv[]) {
835 fprintf(stderr, "Invalid number of arguments.\n");
842 int debuglevel = atoi(argv[1]);
845 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
846 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
847 fprintf(stderr, "Could not set debug level.\n");
851 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
855 static int cmd_retry(int argc, char *argv[]) {
859 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
860 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
861 fprintf(stderr, "Could not retry outgoing connections.\n");
868 static int cmd_connect(int argc, char *argv[]) {
870 fprintf(stderr, "Invalid number of arguments.\n");
874 if(!check_id(argv[2])) {
875 fprintf(stderr, "Invalid name for node.\n");
882 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
883 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
884 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
891 static int cmd_disconnect(int argc, char *argv[]) {
893 fprintf(stderr, "Invalid number of arguments.\n");
897 if(!check_id(argv[2])) {
898 fprintf(stderr, "Invalid name for node.\n");
905 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
906 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
907 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
914 static int cmd_top(int argc, char *argv[]) {
922 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
927 static int cmd_pcap(int argc, char *argv[]) {
931 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
935 static int cmd_log(int argc, char *argv[]) {
939 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
943 static int cmd_pid(int argc, char *argv[]) {
951 static int rstrip(char *value) {
952 int len = strlen(value);
953 while(len && strchr("\t\r\n ", value[len - 1]))
958 static char *get_my_name() {
959 FILE *f = fopen(tinc_conf, "r");
961 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
967 while(fgets(buf, sizeof buf, f)) {
968 int len = strcspn(buf, "\t =");
970 value += strspn(value, "\t ");
973 value += strspn(value, "\t ");
978 if(strcasecmp(buf, "Name"))
982 return strdup(value);
987 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
991 #define VAR_SERVER 1 /* Should be in tinc.conf */
992 #define VAR_HOST 2 /* Can be in host config file */
993 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
994 #define VAR_OBSOLETE 8 /* Should not be used anymore */
999 } const variables[] = {
1000 /* Server configuration */
1001 {"AddressFamily", VAR_SERVER},
1002 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1003 {"BindToInterface", VAR_SERVER},
1004 {"Broadcast", VAR_SERVER},
1005 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1006 {"DecrementTTL", VAR_SERVER},
1007 {"Device", VAR_SERVER},
1008 {"DeviceType", VAR_SERVER},
1009 {"DirectOnly", VAR_SERVER},
1010 {"ECDSAPrivateKeyFile", VAR_SERVER},
1011 {"ExperimentalProtocol", VAR_SERVER},
1012 {"Forwarding", VAR_SERVER},
1013 {"GraphDumpFile", VAR_SERVER},
1014 {"Hostnames", VAR_SERVER},
1015 {"IffOneQueue", VAR_SERVER},
1016 {"Interface", VAR_SERVER},
1017 {"KeyExpire", VAR_SERVER},
1018 {"LocalDiscovery", VAR_SERVER},
1019 {"MACExpire", VAR_SERVER},
1020 {"MaxTimeout", VAR_SERVER},
1021 {"Mode", VAR_SERVER},
1022 {"Name", VAR_SERVER},
1023 {"PingInterval", VAR_SERVER},
1024 {"PingTimeout", VAR_SERVER},
1025 {"PriorityInheritance", VAR_SERVER},
1026 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1027 {"PrivateKeyFile", VAR_SERVER},
1028 {"ProcessPriority", VAR_SERVER},
1029 {"ReplayWindow", VAR_SERVER},
1030 {"StrictSubnets", VAR_SERVER},
1031 {"TunnelServer", VAR_SERVER},
1032 {"UDPRcvBuf", VAR_SERVER},
1033 {"UDPSndBuf", VAR_SERVER},
1034 /* Host configuration */
1035 {"Address", VAR_HOST | VAR_MULTIPLE},
1036 {"Cipher", VAR_SERVER | VAR_HOST},
1037 {"ClampMSS", VAR_SERVER | VAR_HOST},
1038 {"Compression", VAR_SERVER | VAR_HOST},
1039 {"Digest", VAR_SERVER | VAR_HOST},
1040 {"IndirectData", VAR_SERVER | VAR_HOST},
1041 {"MACLength", VAR_SERVER | VAR_HOST},
1042 {"PMTU", VAR_SERVER | VAR_HOST},
1043 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1045 {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1046 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1047 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1048 {"TCPOnly", VAR_SERVER | VAR_HOST},
1052 static int cmd_config(int argc, char *argv[]) {
1054 fprintf(stderr, "Invalid number of arguments.\n");
1059 if(!strcasecmp(argv[1], "add")) {
1060 argv++, argc--, action = 1;
1061 } else if(!strcasecmp(argv[1], "del")) {
1062 argv++, argc--, action = -1;
1063 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1064 argv++, argc--, action = 0;
1068 fprintf(stderr, "Invalid number of arguments.\n");
1072 // Concatenate the rest of the command line
1073 strncpy(line, argv[1], sizeof line - 1);
1074 for(int i = 2; i < argc; i++) {
1075 strncat(line, " ", sizeof line - 1 - strlen(line));
1076 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1079 // Liberal parsing into node name, variable name and value.
1085 len = strcspn(line, "\t =");
1087 value += strspn(value, "\t ");
1090 value += strspn(value, "\t ");
1093 variable = strchr(line, '.');
1102 fprintf(stderr, "No variable given.\n");
1106 if(action >= 0 && !*value) {
1107 fprintf(stderr, "No value for variable given.\n");
1111 /* Some simple checks. */
1114 for(int i = 0; variables[i].name; i++) {
1115 if(strcasecmp(variables[i].name, variable))
1119 variable = (char *)variables[i].name;
1121 /* Discourage use of obsolete variables. */
1123 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1125 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1127 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1132 /* Don't put server variables in host config files */
1134 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1136 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1138 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1143 /* Should this go into our own host config file? */
1145 if(!node && !(variables[i].type & VAR_SERVER)) {
1146 node = get_my_name();
1154 if(node && !check_id(node)) {
1155 fprintf(stderr, "Invalid name for node.\n");
1159 if(!found && action >= 0) {
1161 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1163 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1168 // Open the right configuration file.
1171 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1173 filename = tinc_conf;
1175 FILE *f = fopen(filename, "r");
1177 if(action < 0 || errno != ENOENT) {
1178 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1182 // If it doesn't exist, create it.
1183 f = fopen(filename, "a+");
1185 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1188 fprintf(stderr, "Created configuration file %s.\n", filename);
1193 xasprintf(&tmpfile, "%s.config.tmp", filename);
1194 FILE *tf = fopen(tmpfile, "w");
1196 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1200 // Copy the file, making modifications on the fly.
1204 bool removed = false;
1206 while(fgets(buf1, sizeof buf1, f)) {
1207 buf1[sizeof buf1 - 1] = 0;
1208 strncpy(buf2, buf1, sizeof buf2);
1210 // Parse line in a simple way
1214 len = strcspn(buf2, "\t =");
1215 bvalue = buf2 + len;
1216 bvalue += strspn(bvalue, "\t ");
1217 if(*bvalue == '=') {
1219 bvalue += strspn(bvalue, "\t ");
1225 if(!strcasecmp(buf2, variable)) {
1228 if(!*value || !strcasecmp(bvalue, value)) {
1233 } else if(action == 0) {
1234 // Already set? Delete the rest...
1237 // Otherwise, replace.
1238 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1239 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1247 // Copy original line...
1248 if(fputs(buf1, tf) < 0) {
1249 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1253 // Add newline if it is missing...
1254 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1255 if(fputc('\n', tf) < 0) {
1256 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1262 // Make sure we read everything...
1263 if(ferror(f) || !feof(f)) {
1264 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1269 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1273 // Add new variable if necessary.
1274 if(action > 0 || (action == 0 && !set)) {
1275 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1276 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1281 // Make sure we wrote everything...
1283 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1287 // Could we find what we had to remove?
1288 if(action < 0 && !removed) {
1290 fprintf(stderr, "No configuration variables deleted.\n");
1294 // Replace the configuration file with the new one
1296 if(remove(filename)) {
1297 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1301 if(rename(tmpfile, filename)) {
1302 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1306 // Silently try notifying a running tincd of changes.
1310 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1315 bool check_id(const char *name) {
1316 for(int i = 0; i < strlen(name); i++) {
1317 if(!isalnum(name[i]) && name[i] != '_')
1324 static int cmd_init(int argc, char *argv[]) {
1325 if(!access(tinc_conf, F_OK)) {
1326 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1331 if(isatty(0) && isatty(1)) {
1333 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1335 if(!fgets(buf, sizeof buf, stdin)) {
1336 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1339 int len = rstrip(buf);
1341 fprintf(stderr, "No name given!\n");
1346 fprintf(stderr, "No Name given!\n");
1350 name = strdup(argv[1]);
1352 fprintf(stderr, "No Name given!\n");
1357 if(!check_id(name)) {
1358 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1362 if(mkdir(confdir, 0755) && errno != EEXIST) {
1363 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1367 if(mkdir(confbase, 0755) && errno != EEXIST) {
1368 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1372 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1373 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1377 FILE *f = fopen(tinc_conf, "w");
1379 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1383 fprintf(f, "Name = %s\n", name);
1387 if(!rsa_keygen(2048) || !ecdsa_keygen())
1392 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1393 if(access(filename, F_OK)) {
1394 FILE *f = fopen(filename, "w");
1396 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1399 fchmod(fileno(f), 0755);
1400 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");
1409 static int cmd_generate_keys(int argc, char *argv[]) {
1410 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1413 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1414 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1417 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1418 return !ecdsa_keygen();
1421 static int cmd_help(int argc, char *argv[]) {
1426 static int cmd_version(int argc, char *argv[]) {
1431 static int cmd_info(int argc, char *argv[]) {
1433 fprintf(stderr, "Invalid number of arguments.\n");
1437 if(!connect_tincd())
1440 return info(fd, argv[1]);
1443 static const char *conffiles[] = {
1454 static int cmd_edit(int argc, char *argv[]) {
1456 fprintf(stderr, "Invalid number of arguments.\n");
1460 char *filename = NULL;
1462 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1463 for(int i = 0; conffiles[i]; i++) {
1464 if(!strcmp(argv[1], conffiles[i])) {
1465 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1474 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1475 char *dash = strchr(argv[1], '-');
1478 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1479 fprintf(stderr, "Invalid configuration filename.\n");
1487 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1489 xasprintf(&command, "edit \"%s\"", filename);
1491 int result = system(command);
1495 // Silently try notifying a running tincd of changes.
1499 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1504 static int export(const char *name, FILE *out) {
1506 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1507 FILE *in = fopen(filename, "r");
1509 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1513 fprintf(out, "Name = %s\n", name);
1515 while(fgets(buf, sizeof buf, in)) {
1516 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1521 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1529 static int cmd_export(int argc, char *argv[]) {
1530 char *name = get_my_name();
1534 return export(name, stdout);
1537 static int cmd_export_all(int argc, char *argv[]) {
1538 DIR *dir = opendir(hosts_dir);
1540 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1548 while((ent = readdir(dir))) {
1549 if(!check_id(ent->d_name))
1555 printf("#---------------------------------------------------------------#\n");
1557 result |= export(ent->d_name, stdout);
1564 static int cmd_import(int argc, char *argv[]) {
1572 bool firstline = true;
1574 while(fgets(buf, sizeof buf, in)) {
1575 if(sscanf(buf, "Name = %s", name) == 1) {
1576 if(!check_id(name)) {
1577 fprintf(stderr, "Invalid Name in input!\n");
1585 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1587 if(!force && !access(filename, F_OK)) {
1588 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1593 out = fopen(filename, "w");
1595 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1602 } else if(firstline) {
1603 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1608 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1612 if(fputs(buf, out) < 0) {
1613 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1623 fprintf(stderr, "Imported %d host configuration files.\n", count);
1626 fprintf(stderr, "No host configuration files imported.\n");
1631 static const struct {
1632 const char *command;
1633 int (*function)(int argc, char *argv[]);
1635 {"start", cmd_start},
1637 {"restart", cmd_restart},
1638 {"reload", cmd_reload},
1640 {"purge", cmd_purge},
1641 {"debug", cmd_debug},
1642 {"retry", cmd_retry},
1643 {"connect", cmd_connect},
1644 {"disconnect", cmd_disconnect},
1649 {"config", cmd_config},
1651 {"generate-keys", cmd_generate_keys},
1652 {"generate-rsa-keys", cmd_generate_rsa_keys},
1653 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1655 {"version", cmd_version},
1658 {"export", cmd_export},
1659 {"export-all", cmd_export_all},
1660 {"import", cmd_import},
1664 int main(int argc, char *argv[]) {
1665 program_name = argv[0];
1667 if(!parse_options(argc, argv))
1682 if(optind >= argc) {
1683 fprintf(stderr, "No command given.\n");
1688 for(int i = 0; commands[i].command; i++) {
1689 if(!strcasecmp(argv[optind], commands[i].command))
1690 return commands[i].function(argc - optind, argv + optind);
1693 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);