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"
33 /* The name this program was run with. */
34 static char *program_name = NULL;
36 /* If nonzero, display usage information and exit. */
37 static bool show_help = false;
39 /* If nonzero, print the version on standard output and exit. */
40 static bool show_version = false;
42 static char *name = NULL;
43 static char *identname = NULL; /* program name for syslog */
44 static char *pidfilename = NULL; /* pid file location */
45 static char controlcookie[1024];
47 char *confbase = NULL;
48 static char *tinc_conf = NULL;
49 static char *hosts_dir = NULL;
51 // Horrible global variables...
54 static char line[4096];
60 static struct WSAData wsa_state;
63 static struct option const long_options[] = {
64 {"config", required_argument, NULL, 'c'},
65 {"debug", optional_argument, NULL, 0},
66 {"no-detach", no_argument, NULL, 0},
67 {"mlock", no_argument, NULL, 0},
68 {"net", required_argument, NULL, 'n'},
69 {"help", no_argument, NULL, 1},
70 {"version", no_argument, NULL, 2},
71 {"pidfile", required_argument, NULL, 5},
72 {"logfile", required_argument, NULL, 0},
73 {"bypass-security", no_argument, NULL, 0},
74 {"chroot", no_argument, NULL, 0},
75 {"user", required_argument, NULL, 0},
76 {"option", required_argument, NULL, 0},
80 static void version(void) {
81 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
82 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
83 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
84 "See the AUTHORS file for a complete list.\n\n"
85 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
86 "and you are welcome to redistribute it under certain conditions;\n"
87 "see the file COPYING for details.\n");
90 static void usage(bool status) {
92 fprintf(stderr, "Try `%s --help\' for more information.\n",
95 printf("Usage: %s [options] command\n\n", program_name);
96 printf("Valid options are:\n"
97 " -c, --config=DIR Read configuration options from DIR.\n"
98 " -n, --net=NETNAME Connect to net NETNAME.\n"
99 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
100 " --help Display this help and exit.\n"
101 " --version Output version information and exit.\n"
103 "Valid commands are:\n"
104 " init [name] Create initial configuration files.\n"
105 " config Change configuration:\n"
106 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
107 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
108 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
109 " start [tincd options] Start tincd.\n"
110 " stop Stop tincd.\n"
111 " restart Restart tincd.\n"
112 " reload Partially reload configuration of running tincd.\n"
113 " pid Show PID of currently running tincd.\n"
114 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
115 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
116 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
117 " dump Dump a list of one of the following things:\n"
118 " nodes - all known nodes in the VPN\n"
119 " edges - all known connections in the VPN\n"
120 " subnets - all known subnets in the VPN\n"
121 " connections - all meta connections with ourself\n"
122 " graph - graph of the VPN in dotty format\n"
123 " purge Purge unreachable nodes\n"
124 " debug N Set debug level\n"
125 " retry Retry all outgoing connections\n"
126 " disconnect NODE Close meta connection with NODE\n"
128 " top Show real-time statistics\n"
130 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
131 " log [level] Dump log output [up to the specified level]\n"
133 printf("Report bugs to tinc@tinc-vpn.org.\n");
137 static bool parse_options(int argc, char **argv) {
139 int option_index = 0;
141 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
143 case 0: /* long option */
146 case 'c': /* config file */
147 confbase = xstrdup(optarg);
150 case 'n': /* net name given */
151 netname = xstrdup(optarg);
154 case 1: /* show help */
158 case 2: /* show version */
162 case 5: /* open control socket here */
163 pidfilename = xstrdup(optarg);
176 netname = getenv("NETNAME");
178 netname = xstrdup(netname);
184 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
190 /* Check stdin and stdout */
191 if(isatty(0) && isatty(1)) {
192 /* Ask for a file and/or directory name. */
193 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
197 if(fgets(buf, sizeof buf, stdin) == NULL) {
198 fprintf(stderr, "Error while reading stdin: %s\n",
203 size_t len = strlen(buf);
212 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
214 if(filename[0] != '/') {
216 /* The directory is a relative path or a filename. */
217 directory = get_current_dir_name();
218 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
222 umask(0077); /* Disallow everything for group and other */
224 /* Open it first to keep the inode busy */
226 r = fopen(filename, mode);
229 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
237 Generate a public/private ECDSA keypair, and ask for a file to store
240 static bool ecdsa_keygen() {
245 fprintf(stderr, "Generating ECDSA keypair:\n");
247 if(!ecdsa_generate(&key)) {
248 fprintf(stderr, "Error during key generation!\n");
251 fprintf(stderr, "Done.\n");
253 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
254 f = ask_and_open(filename, "private ECDSA key", "a");
260 /* Make it unreadable for others. */
261 fchmod(fileno(f), 0600);
265 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
267 ecdsa_write_pem_private_key(&key, f);
273 xasprintf(&filename, "%s/hosts/%s", confbase, name);
275 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
277 f = ask_and_open(filename, "public ECDSA key", "a");
283 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
285 char *pubkey = ecdsa_get_base64_public_key(&key);
286 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
296 Generate a public/private RSA keypair, and ask for a file to store
299 static bool rsa_keygen(int bits) {
304 fprintf(stderr, "Generating %d bits keys:\n", bits);
306 if(!rsa_generate(&key, bits, 0x10001)) {
307 fprintf(stderr, "Error during key generation!\n");
310 fprintf(stderr, "Done.\n");
312 xasprintf(&filename, "%s/rsa_key.priv", confbase);
313 f = ask_and_open(filename, "private RSA key", "a");
319 /* Make it unreadable for others. */
320 fchmod(fileno(f), 0600);
324 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
326 rsa_write_pem_private_key(&key, f);
332 xasprintf(&filename, "%s/hosts/%s", confbase, name);
334 xasprintf(&filename, "%s/rsa_key.pub", confbase);
336 f = ask_and_open(filename, "public RSA key", "a");
342 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
344 rsa_write_pem_public_key(&key, f);
353 Set all files and paths according to netname
355 static void make_names(void) {
358 char installdir[1024] = "";
359 long len = sizeof installdir;
363 xasprintf(&identname, "tinc.%s", netname);
365 identname = xstrdup("tinc");
368 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
369 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
372 xasprintf(&confbase, "%s/%s", installdir, netname);
374 xasprintf(&confbase, "%s", installdir);
378 xasprintf(&pidfilename, "%s/pid", confbase);
386 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
390 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
392 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
395 xasprintf(&confbase, CONFDIR "/tinc");
402 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
403 xasprintf(&hosts_dir, "%s/hosts", confbase);
406 static char buffer[4096];
407 static size_t blen = 0;
409 bool recvline(int fd, char *line, size_t len) {
410 char *newline = NULL;
412 while(!(newline = memchr(buffer, '\n', blen))) {
413 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
414 if(result == -1 && errno == EINTR)
421 if(newline - buffer >= len)
424 len = newline - buffer;
426 memcpy(line, buffer, len);
428 memmove(buffer, newline + 1, blen - len - 1);
434 static bool recvdata(int fd, char *data, size_t len) {
436 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
437 if(result == -1 && errno == EINTR)
444 memcpy(data, buffer, len);
445 memmove(buffer, buffer + len, blen - len);
451 bool sendline(int fd, char *format, ...) {
452 static char buffer[4096];
457 va_start(ap, format);
458 blen = vsnprintf(buffer, sizeof buffer, format, ap);
461 if(blen < 1 || blen >= sizeof buffer)
468 int result = send(fd, p, blen, 0);
469 if(result == -1 && errno == EINTR)
480 static void pcap(int fd, FILE *out, int snaplen) {
481 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
489 uint32_t tz_accuracy;
496 snaplen ?: sizeof data,
509 fwrite(&header, sizeof header, 1, out);
513 while(recvline(fd, line, sizeof line)) {
515 int n = sscanf(line, "%d %d %d", &code, &req, &len);
516 gettimeofday(&tv, NULL);
517 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
519 if(!recvdata(fd, data, len))
521 packet.tv_sec = tv.tv_sec;
522 packet.tv_usec = tv.tv_usec;
524 packet.origlen = len;
525 fwrite(&packet, sizeof packet, 1, out);
526 fwrite(data, len, 1, out);
531 static void logcontrol(int fd, FILE *out, int level) {
532 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
536 while(recvline(fd, line, sizeof line)) {
538 int n = sscanf(line, "%d %d %d", &code, &req, &len);
539 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
541 if(!recvdata(fd, data, len))
543 fwrite(data, len, 1, out);
550 static bool remove_service(void) {
551 SC_HANDLE manager = NULL;
552 SC_HANDLE service = NULL;
553 SERVICE_STATUS status = {0};
555 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
557 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
561 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
564 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
568 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
569 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
571 fprintf(stderr, "%s service stopped\n", identname);
573 if(!DeleteService(service)) {
574 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
578 fprintf(stderr, "%s service removed\n", identname);
584 static bool connect_tincd() {
588 FILE *f = fopen(pidfilename, "r");
590 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
597 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
598 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
603 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
604 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
609 struct addrinfo hints = {
610 .ai_family = AF_UNSPEC,
611 .ai_socktype = SOCK_STREAM,
612 .ai_protocol = IPPROTO_TCP,
616 struct addrinfo *res = NULL;
618 if(getaddrinfo(host, port, &hints, &res) || !res) {
619 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
623 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
625 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
630 unsigned long arg = 0;
632 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
633 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
637 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
638 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
647 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
648 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
652 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
654 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
655 fprintf(stderr, "Could not fully establish control socket connection\n");
663 static int cmd_start(int argc, char *argv[]) {
669 char *slash = strrchr(argv[0], '/');
672 if ((c = strrchr(argv[0], '\\')) > slash)
677 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
678 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
685 for(i = j = 1; argv[i]; ++i)
686 if (i != optind && strcmp(argv[i], "--") != 0)
691 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
695 static int cmd_stop(int argc, char *argv[]) {
700 sendline(fd, "%d %d", CONTROL, REQ_STOP);
701 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
702 fprintf(stderr, "Could not stop tinc daemon.\n");
706 if(!remove_service())
712 static int cmd_restart(int argc, char *argv[]) {
713 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
716 static int cmd_reload(int argc, char *argv[]) {
720 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
721 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
722 fprintf(stderr, "Could not reload configuration.\n");
730 static int cmd_dump(int argc, char *argv[]) {
732 fprintf(stderr, "Invalid number of arguments.\n");
737 bool do_graph = false;
739 if(!strcasecmp(argv[1], "nodes"))
740 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
741 else if(!strcasecmp(argv[1], "edges"))
742 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
743 else if(!strcasecmp(argv[1], "subnets"))
744 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
745 else if(!strcasecmp(argv[1], "connections"))
746 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
747 else if(!strcasecmp(argv[1], "graph")) {
748 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
749 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
752 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
761 printf("digraph {\n");
763 while(recvline(fd, line, sizeof line)) {
764 char node1[4096], node2[4096];
765 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
767 if(do_graph && req == REQ_DUMP_NODES)
779 printf("%s\n", line + 5);
781 if(req == REQ_DUMP_NODES)
782 printf(" %s [label = \"%s\"];\n", node1, node1);
784 printf(" %s -> %s;\n", node1, node2);
788 fprintf(stderr, "Error receiving dump.\n");
792 static int cmd_purge(int argc, char *argv[]) {
796 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
797 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
798 fprintf(stderr, "Could not purge old information.\n");
805 static int cmd_debug(int argc, char *argv[]) {
807 fprintf(stderr, "Invalid number of arguments.\n");
814 int debuglevel = atoi(argv[1]);
817 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
818 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
819 fprintf(stderr, "Could not set debug level.\n");
823 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
827 static int cmd_retry(int argc, char *argv[]) {
831 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
832 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
833 fprintf(stderr, "Could not retry outgoing connections.\n");
840 static int cmd_connect(int argc, char *argv[]) {
842 fprintf(stderr, "Invalid number of arguments.\n");
846 if(!check_id(argv[2])) {
847 fprintf(stderr, "Invalid name for node.\n");
854 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
855 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
856 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
863 static int cmd_disconnect(int argc, char *argv[]) {
865 fprintf(stderr, "Invalid number of arguments.\n");
869 if(!check_id(argv[2])) {
870 fprintf(stderr, "Invalid name for node.\n");
877 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
878 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
879 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
886 static int cmd_top(int argc, char *argv[]) {
894 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
899 static int cmd_pcap(int argc, char *argv[]) {
903 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
907 static int cmd_log(int argc, char *argv[]) {
911 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
915 static int cmd_pid(int argc, char *argv[]) {
923 static int rstrip(char *value) {
924 int len = strlen(value);
925 while(len && strchr("\t\r\n ", value[len - 1]))
930 static char *get_my_name() {
931 FILE *f = fopen(tinc_conf, "r");
933 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
939 while(fgets(buf, sizeof buf, f)) {
940 int len = strcspn(buf, "\t =");
942 value += strspn(value, "\t ");
945 value += strspn(value, "\t ");
950 if(strcasecmp(buf, "Name"))
954 return strdup(value);
959 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
963 static char *hostvariables[] = {
971 static int cmd_config(int argc, char *argv[]) {
973 fprintf(stderr, "Invalid number of arguments.\n");
978 if(!strcasecmp(argv[1], "add")) {
979 argv++, argc--, action = 1;
980 } else if(!strcasecmp(argv[1], "del")) {
981 argv++, argc--, action = -1;
982 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
983 argv++, argc--, action = 0;
987 fprintf(stderr, "Invalid number of arguments.\n");
991 // Concatenate the rest of the command line
992 strncpy(line, argv[1], sizeof line - 1);
993 for(int i = 2; i < argc; i++) {
994 strncat(line, " ", sizeof line - 1 - strlen(line));
995 strncat(line, argv[i], sizeof line - 1 - strlen(line));
998 // Liberal parsing into node name, variable name and value.
1004 len = strcspn(line, "\t =");
1006 value += strspn(value, "\t ");
1009 value += strspn(value, "\t ");
1012 variable = strchr(line, '.');
1021 fprintf(stderr, "No variable given.\n");
1025 if(action >= 0 && !*value) {
1026 fprintf(stderr, "No value for variable given.\n");
1030 // Should this go into our own host config file?
1032 for(int i = 0; hostvariables[i]; i++) {
1033 if(!strcasecmp(hostvariables[i], variable)) {
1034 node = get_my_name();
1042 if(node && !check_id(node)) {
1043 fprintf(stderr, "Invalid name for node.\n");
1047 // Open the right configuration file.
1050 xasprintf(&filename, "%s/%s", hosts_dir, node);
1052 filename = tinc_conf;
1054 FILE *f = fopen(filename, "r");
1056 if(action < 0 || errno != ENOENT) {
1057 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1061 // If it doesn't exist, create it.
1062 f = fopen(filename, "a+");
1064 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1067 fprintf(stderr, "Created configuration file %s.\n", filename);
1072 xasprintf(&tmpfile, "%s.config.tmp", filename);
1073 FILE *tf = fopen(tmpfile, "w");
1075 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1079 // Copy the file, making modifications on the fly.
1083 bool removed = false;
1085 while(fgets(buf1, sizeof buf1, f)) {
1086 buf1[sizeof buf1 - 1] = 0;
1089 // Parse line in a simple way
1093 len = strcspn(buf2, "\t =");
1094 bvalue = buf2 + len;
1095 bvalue += strspn(bvalue, "\t ");
1096 if(*bvalue == '=') {
1098 bvalue += strspn(bvalue, "\t ");
1104 if(!strcasecmp(buf2, variable)) {
1107 if(!*value || !strcasecmp(bvalue, value)) {
1112 } else if(action == 0) {
1113 // Already set? Delete the rest...
1116 // Otherwise, replace.
1117 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1118 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1126 // Copy original line...
1127 if(fputs(buf1, tf) < 0) {
1128 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1133 // Make sure we read everything...
1134 if(ferror(f) || !feof(f)) {
1135 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1140 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1144 // Add new variable if necessary.
1145 if(action > 0 || (action == 0 && !set)) {
1146 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1147 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1152 // Make sure we wrote everything...
1154 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1158 // Could we find what we had to remove?
1159 if(action < 0 && !removed) {
1161 fprintf(stderr, "No configuration variables deleted.\n");
1165 // Replace the configuration file with the new one
1167 if(remove(filename)) {
1168 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1172 if(rename(tmpfile, filename)) {
1173 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1177 // Silently try notifying a running tincd of changes.
1181 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1186 bool check_id(const char *name) {
1187 for(int i = 0; i < strlen(name); i++) {
1188 if(!isalnum(name[i]) && name[i] != '_')
1195 static int cmd_init(int argc, char *argv[]) {
1196 if(!access(tinc_conf, F_OK)) {
1197 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1202 if(isatty(0) && isatty(1)) {
1204 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1206 if(!fgets(buf, sizeof buf, stdin)) {
1207 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1210 int len = rstrip(buf);
1212 fprintf(stderr, "No name given!\n");
1217 fprintf(stderr, "No Name given!\n");
1221 name = strdup(argv[1]);
1223 fprintf(stderr, "No Name given!\n");
1228 if(!check_id(name)) {
1229 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1233 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1234 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1238 if(mkdir(confbase, 0755) && errno != EEXIST) {
1239 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1243 char *hosts_dir = NULL;
1244 xasprintf(&hosts_dir, "%s/hosts", confbase);
1245 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1246 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1250 FILE *f = fopen(tinc_conf, "w");
1252 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1256 fprintf(f, "Name = %s\n", name);
1260 if(!rsa_keygen(2048) || !ecdsa_keygen())
1267 static int cmd_generate_keys(int argc, char *argv[]) {
1268 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1271 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1272 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1275 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1276 return !ecdsa_keygen();
1279 static int cmd_help(int argc, char *argv[]) {
1284 static int cmd_version(int argc, char *argv[]) {
1289 static const char *conffiles[] = {
1300 static int cmd_edit(int argc, char *argv[]) {
1302 fprintf(stderr, "Invalid number of arguments.\n");
1306 char *filename = NULL;
1308 if(strncmp(argv[1], "hosts/", 6)) {
1309 for(int i = 0; conffiles[i]; i++) {
1310 if(!strcmp(argv[1], conffiles[i])) {
1311 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1320 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1321 char *dash = strchr(argv[1], '-');
1324 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1325 fprintf(stderr, "Invalid configuration filename.\n");
1332 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1334 char *editor = "edit"
1338 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1339 int result = system(command);
1343 // Silently try notifying a running tincd of changes.
1347 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1352 static const struct {
1353 const char *command;
1354 int (*function)(int argc, char *argv[]);
1356 {"start", cmd_start},
1358 {"restart", cmd_restart},
1359 {"reload", cmd_reload},
1361 {"purge", cmd_purge},
1362 {"debug", cmd_debug},
1363 {"retry", cmd_retry},
1364 {"connect", cmd_connect},
1365 {"disconnect", cmd_disconnect},
1370 {"config", cmd_config},
1372 {"generate-keys", cmd_generate_keys},
1373 {"generate-rsa-keys", cmd_generate_rsa_keys},
1374 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1376 {"version", cmd_version},
1381 int main(int argc, char *argv[]) {
1382 program_name = argv[0];
1384 if(!parse_options(argc, argv))
1399 if(optind >= argc) {
1400 fprintf(stderr, "No command given.\n");
1405 for(int i = 0; commands[i].command; i++) {
1406 if(!strcasecmp(argv[optind], commands[i].command))
1407 return commands[i].function(argc - optind, argv + optind);
1410 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);