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"
34 /* The name this program was run with. */
35 static char *program_name = NULL;
37 /* If nonzero, display usage information and exit. */
38 static bool show_help = false;
40 /* If nonzero, print the version on standard output and exit. */
41 static bool show_version = false;
43 static char *name = NULL;
44 static char *identname = NULL; /* program name for syslog */
45 static char *pidfilename = NULL; /* pid file location */
46 static char controlcookie[1024];
48 char *confbase = NULL;
49 static char *tinc_conf = NULL;
50 static char *hosts_dir = NULL;
52 // Horrible global variables...
55 static char line[4096];
61 static struct WSAData wsa_state;
64 static struct option const long_options[] = {
65 {"config", required_argument, NULL, 'c'},
66 {"debug", optional_argument, NULL, 0},
67 {"no-detach", no_argument, NULL, 0},
68 {"mlock", no_argument, NULL, 0},
69 {"net", required_argument, NULL, 'n'},
70 {"help", no_argument, NULL, 1},
71 {"version", no_argument, NULL, 2},
72 {"pidfile", required_argument, NULL, 5},
73 {"logfile", required_argument, NULL, 0},
74 {"bypass-security", no_argument, NULL, 0},
75 {"chroot", no_argument, NULL, 0},
76 {"user", required_argument, NULL, 0},
77 {"option", required_argument, NULL, 0},
81 static void version(void) {
82 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
83 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
84 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
85 "See the AUTHORS file for a complete list.\n\n"
86 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
87 "and you are welcome to redistribute it under certain conditions;\n"
88 "see the file COPYING for details.\n");
91 static void usage(bool status) {
93 fprintf(stderr, "Try `%s --help\' for more information.\n",
96 printf("Usage: %s [options] command\n\n", program_name);
97 printf("Valid options are:\n"
98 " -c, --config=DIR Read configuration options from DIR.\n"
99 " -n, --net=NETNAME Connect to net NETNAME.\n"
100 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
101 " --help Display this help and exit.\n"
102 " --version Output version information and exit.\n"
104 "Valid commands are:\n"
105 " init [name] Create initial configuration files.\n"
106 " config Change configuration:\n"
107 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
108 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
109 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
110 " start [tincd options] Start tincd.\n"
111 " stop Stop tincd.\n"
112 " restart Restart tincd.\n"
113 " reload Partially reload configuration of running tincd.\n"
114 " pid Show PID of currently running tincd.\n"
115 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
116 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
117 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
118 " dump Dump a list of one of the following things:\n"
119 " nodes - all known nodes in the VPN\n"
120 " edges - all known connections in the VPN\n"
121 " subnets - all known subnets in the VPN\n"
122 " connections - all meta connections with ourself\n"
123 " graph - graph of the VPN in dotty format\n"
124 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
125 " purge Purge unreachable nodes\n"
126 " debug N Set debug level\n"
127 " retry Retry all outgoing connections\n"
128 " disconnect NODE Close meta connection with NODE\n"
130 " top Show real-time statistics\n"
132 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
133 " log [level] Dump log output [up to the specified level]\n"
135 printf("Report bugs to tinc@tinc-vpn.org.\n");
139 static bool parse_options(int argc, char **argv) {
141 int option_index = 0;
143 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
145 case 0: /* long option */
148 case 'c': /* config file */
149 confbase = xstrdup(optarg);
152 case 'n': /* net name given */
153 netname = xstrdup(optarg);
156 case 1: /* show help */
160 case 2: /* show version */
164 case 5: /* open control socket here */
165 pidfilename = xstrdup(optarg);
178 netname = getenv("NETNAME");
180 netname = xstrdup(netname);
186 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
192 /* Check stdin and stdout */
193 if(isatty(0) && isatty(1)) {
194 /* Ask for a file and/or directory name. */
195 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
199 if(fgets(buf, sizeof buf, stdin) == NULL) {
200 fprintf(stderr, "Error while reading stdin: %s\n",
205 size_t len = strlen(buf);
214 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
216 if(filename[0] != '/') {
218 /* The directory is a relative path or a filename. */
219 directory = get_current_dir_name();
220 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
224 umask(0077); /* Disallow everything for group and other */
226 /* Open it first to keep the inode busy */
228 r = fopen(filename, mode);
231 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
239 Generate a public/private ECDSA keypair, and ask for a file to store
242 static bool ecdsa_keygen() {
247 fprintf(stderr, "Generating ECDSA keypair:\n");
249 if(!ecdsa_generate(&key)) {
250 fprintf(stderr, "Error during key generation!\n");
253 fprintf(stderr, "Done.\n");
255 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
256 f = ask_and_open(filename, "private ECDSA key", "a");
262 /* Make it unreadable for others. */
263 fchmod(fileno(f), 0600);
267 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
269 ecdsa_write_pem_private_key(&key, f);
275 xasprintf(&filename, "%s/hosts/%s", confbase, name);
277 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
279 f = ask_and_open(filename, "public ECDSA key", "a");
285 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
287 char *pubkey = ecdsa_get_base64_public_key(&key);
288 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
298 Generate a public/private RSA keypair, and ask for a file to store
301 static bool rsa_keygen(int bits) {
306 fprintf(stderr, "Generating %d bits keys:\n", bits);
308 if(!rsa_generate(&key, bits, 0x10001)) {
309 fprintf(stderr, "Error during key generation!\n");
312 fprintf(stderr, "Done.\n");
314 xasprintf(&filename, "%s/rsa_key.priv", confbase);
315 f = ask_and_open(filename, "private RSA key", "a");
321 /* Make it unreadable for others. */
322 fchmod(fileno(f), 0600);
326 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
328 rsa_write_pem_private_key(&key, f);
334 xasprintf(&filename, "%s/hosts/%s", confbase, name);
336 xasprintf(&filename, "%s/rsa_key.pub", confbase);
338 f = ask_and_open(filename, "public RSA key", "a");
344 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
346 rsa_write_pem_public_key(&key, f);
355 Set all files and paths according to netname
357 static void make_names(void) {
360 char installdir[1024] = "";
361 long len = sizeof installdir;
365 xasprintf(&identname, "tinc.%s", netname);
367 identname = xstrdup("tinc");
370 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
371 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
374 xasprintf(&confbase, "%s/%s", installdir, netname);
376 xasprintf(&confbase, "%s", installdir);
380 xasprintf(&pidfilename, "%s/pid", confbase);
388 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
392 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
394 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
397 xasprintf(&confbase, CONFDIR "/tinc");
404 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
405 xasprintf(&hosts_dir, "%s/hosts", confbase);
408 static char buffer[4096];
409 static size_t blen = 0;
411 bool recvline(int fd, char *line, size_t len) {
412 char *newline = NULL;
414 while(!(newline = memchr(buffer, '\n', blen))) {
415 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
416 if(result == -1 && errno == EINTR)
423 if(newline - buffer >= len)
426 len = newline - buffer;
428 memcpy(line, buffer, len);
430 memmove(buffer, newline + 1, blen - len - 1);
436 static bool recvdata(int fd, char *data, size_t len) {
438 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
439 if(result == -1 && errno == EINTR)
446 memcpy(data, buffer, len);
447 memmove(buffer, buffer + len, blen - len);
453 bool sendline(int fd, char *format, ...) {
454 static char buffer[4096];
459 va_start(ap, format);
460 blen = vsnprintf(buffer, sizeof buffer, format, ap);
463 if(blen < 1 || blen >= sizeof buffer)
470 int result = send(fd, p, blen, 0);
471 if(result == -1 && errno == EINTR)
482 static void pcap(int fd, FILE *out, int snaplen) {
483 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
491 uint32_t tz_accuracy;
498 snaplen ?: sizeof data,
511 fwrite(&header, sizeof header, 1, out);
515 while(recvline(fd, line, sizeof line)) {
517 int n = sscanf(line, "%d %d %d", &code, &req, &len);
518 gettimeofday(&tv, NULL);
519 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
521 if(!recvdata(fd, data, len))
523 packet.tv_sec = tv.tv_sec;
524 packet.tv_usec = tv.tv_usec;
526 packet.origlen = len;
527 fwrite(&packet, sizeof packet, 1, out);
528 fwrite(data, len, 1, out);
533 static void logcontrol(int fd, FILE *out, int level) {
534 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
538 while(recvline(fd, line, sizeof line)) {
540 int n = sscanf(line, "%d %d %d", &code, &req, &len);
541 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
543 if(!recvdata(fd, data, len))
545 fwrite(data, len, 1, out);
552 static bool remove_service(void) {
553 SC_HANDLE manager = NULL;
554 SC_HANDLE service = NULL;
555 SERVICE_STATUS status = {0};
557 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
559 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
563 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
566 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
570 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
571 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
573 fprintf(stderr, "%s service stopped\n", identname);
575 if(!DeleteService(service)) {
576 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
580 fprintf(stderr, "%s service removed\n", identname);
586 static bool connect_tincd() {
590 FILE *f = fopen(pidfilename, "r");
592 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
599 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
600 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
605 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
606 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
611 struct addrinfo hints = {
612 .ai_family = AF_UNSPEC,
613 .ai_socktype = SOCK_STREAM,
614 .ai_protocol = IPPROTO_TCP,
618 struct addrinfo *res = NULL;
620 if(getaddrinfo(host, port, &hints, &res) || !res) {
621 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
625 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
627 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
632 unsigned long arg = 0;
634 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
635 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
639 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
640 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
649 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
650 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
654 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
656 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
657 fprintf(stderr, "Could not fully establish control socket connection\n");
665 static int cmd_start(int argc, char *argv[]) {
671 char *slash = strrchr(argv[0], '/');
674 if ((c = strrchr(argv[0], '\\')) > slash)
679 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
680 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
687 for(i = j = 1; argv[i]; ++i)
688 if (i != optind && strcmp(argv[i], "--") != 0)
693 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
697 static int cmd_stop(int argc, char *argv[]) {
702 sendline(fd, "%d %d", CONTROL, REQ_STOP);
703 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
704 fprintf(stderr, "Could not stop tinc daemon.\n");
708 if(!remove_service())
714 static int cmd_restart(int argc, char *argv[]) {
715 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
718 static int cmd_reload(int argc, char *argv[]) {
722 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
723 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
724 fprintf(stderr, "Could not reload configuration.\n");
732 static int cmd_dump(int argc, char *argv[]) {
734 fprintf(stderr, "Invalid number of arguments.\n");
742 bool do_graph = false;
744 if(!strcasecmp(argv[1], "nodes"))
745 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
746 else if(!strcasecmp(argv[1], "edges"))
747 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
748 else if(!strcasecmp(argv[1], "subnets"))
749 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
750 else if(!strcasecmp(argv[1], "connections"))
751 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
752 else if(!strcasecmp(argv[1], "graph")) {
753 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
754 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
757 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
763 printf("digraph {\n");
765 while(recvline(fd, line, sizeof line)) {
766 char node1[4096], node2[4096];
767 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
769 if(do_graph && req == REQ_DUMP_NODES)
781 printf("%s\n", line + 5);
783 if(req == REQ_DUMP_NODES)
784 printf(" %s [label = \"%s\"];\n", node1, node1);
786 printf(" %s -> %s;\n", node1, node2);
790 fprintf(stderr, "Error receiving dump.\n");
794 static int cmd_purge(int argc, char *argv[]) {
798 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
799 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
800 fprintf(stderr, "Could not purge old information.\n");
807 static int cmd_debug(int argc, char *argv[]) {
809 fprintf(stderr, "Invalid number of arguments.\n");
816 int debuglevel = atoi(argv[1]);
819 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
820 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
821 fprintf(stderr, "Could not set debug level.\n");
825 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
829 static int cmd_retry(int argc, char *argv[]) {
833 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
834 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
835 fprintf(stderr, "Could not retry outgoing connections.\n");
842 static int cmd_connect(int argc, char *argv[]) {
844 fprintf(stderr, "Invalid number of arguments.\n");
848 if(!check_id(argv[2])) {
849 fprintf(stderr, "Invalid name for node.\n");
856 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
857 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
858 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
865 static int cmd_disconnect(int argc, char *argv[]) {
867 fprintf(stderr, "Invalid number of arguments.\n");
871 if(!check_id(argv[2])) {
872 fprintf(stderr, "Invalid name for node.\n");
879 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
880 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
881 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
888 static int cmd_top(int argc, char *argv[]) {
896 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
901 static int cmd_pcap(int argc, char *argv[]) {
905 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
909 static int cmd_log(int argc, char *argv[]) {
913 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
917 static int cmd_pid(int argc, char *argv[]) {
925 static int rstrip(char *value) {
926 int len = strlen(value);
927 while(len && strchr("\t\r\n ", value[len - 1]))
932 static char *get_my_name() {
933 FILE *f = fopen(tinc_conf, "r");
935 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
941 while(fgets(buf, sizeof buf, f)) {
942 int len = strcspn(buf, "\t =");
944 value += strspn(value, "\t ");
947 value += strspn(value, "\t ");
952 if(strcasecmp(buf, "Name"))
956 return strdup(value);
961 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
965 static char *hostvariables[] = {
973 static int cmd_config(int argc, char *argv[]) {
975 fprintf(stderr, "Invalid number of arguments.\n");
980 if(!strcasecmp(argv[1], "add")) {
981 argv++, argc--, action = 1;
982 } else if(!strcasecmp(argv[1], "del")) {
983 argv++, argc--, action = -1;
984 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
985 argv++, argc--, action = 0;
989 fprintf(stderr, "Invalid number of arguments.\n");
993 // Concatenate the rest of the command line
994 strncpy(line, argv[1], sizeof line - 1);
995 for(int i = 2; i < argc; i++) {
996 strncat(line, " ", sizeof line - 1 - strlen(line));
997 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1000 // Liberal parsing into node name, variable name and value.
1006 len = strcspn(line, "\t =");
1008 value += strspn(value, "\t ");
1011 value += strspn(value, "\t ");
1014 variable = strchr(line, '.');
1023 fprintf(stderr, "No variable given.\n");
1027 if(action >= 0 && !*value) {
1028 fprintf(stderr, "No value for variable given.\n");
1032 // Should this go into our own host config file?
1034 for(int i = 0; hostvariables[i]; i++) {
1035 if(!strcasecmp(hostvariables[i], variable)) {
1036 node = get_my_name();
1044 if(node && !check_id(node)) {
1045 fprintf(stderr, "Invalid name for node.\n");
1049 // Open the right configuration file.
1052 xasprintf(&filename, "%s/%s", hosts_dir, node);
1054 filename = tinc_conf;
1056 FILE *f = fopen(filename, "r");
1058 if(action < 0 || errno != ENOENT) {
1059 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1063 // If it doesn't exist, create it.
1064 f = fopen(filename, "a+");
1066 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1069 fprintf(stderr, "Created configuration file %s.\n", filename);
1074 xasprintf(&tmpfile, "%s.config.tmp", filename);
1075 FILE *tf = fopen(tmpfile, "w");
1077 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1081 // Copy the file, making modifications on the fly.
1085 bool removed = false;
1087 while(fgets(buf1, sizeof buf1, f)) {
1088 buf1[sizeof buf1 - 1] = 0;
1091 // Parse line in a simple way
1095 len = strcspn(buf2, "\t =");
1096 bvalue = buf2 + len;
1097 bvalue += strspn(bvalue, "\t ");
1098 if(*bvalue == '=') {
1100 bvalue += strspn(bvalue, "\t ");
1106 if(!strcasecmp(buf2, variable)) {
1109 if(!*value || !strcasecmp(bvalue, value)) {
1114 } else if(action == 0) {
1115 // Already set? Delete the rest...
1118 // Otherwise, replace.
1119 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1120 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1128 // Copy original line...
1129 if(fputs(buf1, tf) < 0) {
1130 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1135 // Make sure we read everything...
1136 if(ferror(f) || !feof(f)) {
1137 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1142 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1146 // Add new variable if necessary.
1147 if(action > 0 || (action == 0 && !set)) {
1148 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1149 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1154 // Make sure we wrote everything...
1156 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1160 // Could we find what we had to remove?
1161 if(action < 0 && !removed) {
1163 fprintf(stderr, "No configuration variables deleted.\n");
1167 // Replace the configuration file with the new one
1169 if(remove(filename)) {
1170 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1174 if(rename(tmpfile, filename)) {
1175 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1179 // Silently try notifying a running tincd of changes.
1183 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1188 bool check_id(const char *name) {
1189 for(int i = 0; i < strlen(name); i++) {
1190 if(!isalnum(name[i]) && name[i] != '_')
1197 static int cmd_init(int argc, char *argv[]) {
1198 if(!access(tinc_conf, F_OK)) {
1199 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1204 if(isatty(0) && isatty(1)) {
1206 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1208 if(!fgets(buf, sizeof buf, stdin)) {
1209 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1212 int len = rstrip(buf);
1214 fprintf(stderr, "No name given!\n");
1219 fprintf(stderr, "No Name given!\n");
1223 name = strdup(argv[1]);
1225 fprintf(stderr, "No Name given!\n");
1230 if(!check_id(name)) {
1231 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1235 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1236 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1240 if(mkdir(confbase, 0755) && errno != EEXIST) {
1241 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1245 char *hosts_dir = NULL;
1246 xasprintf(&hosts_dir, "%s/hosts", confbase);
1247 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1248 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1252 FILE *f = fopen(tinc_conf, "w");
1254 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1258 fprintf(f, "Name = %s\n", name);
1262 if(!rsa_keygen(2048) || !ecdsa_keygen())
1269 static int cmd_generate_keys(int argc, char *argv[]) {
1270 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1273 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1274 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1277 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1278 return !ecdsa_keygen();
1281 static int cmd_help(int argc, char *argv[]) {
1286 static int cmd_version(int argc, char *argv[]) {
1291 static int cmd_info(int argc, char *argv[]) {
1293 fprintf(stderr, "Invalid number of arguments.\n");
1297 if(!connect_tincd())
1300 return info(fd, argv[1]);
1303 static const char *conffiles[] = {
1314 static int cmd_edit(int argc, char *argv[]) {
1316 fprintf(stderr, "Invalid number of arguments.\n");
1320 char *filename = NULL;
1322 if(strncmp(argv[1], "hosts/", 6)) {
1323 for(int i = 0; conffiles[i]; i++) {
1324 if(!strcmp(argv[1], conffiles[i])) {
1325 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1334 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1335 char *dash = strchr(argv[1], '-');
1338 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1339 fprintf(stderr, "Invalid configuration filename.\n");
1346 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1348 char *editor = "edit"
1352 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1353 int result = system(command);
1357 // Silently try notifying a running tincd of changes.
1361 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1366 static const struct {
1367 const char *command;
1368 int (*function)(int argc, char *argv[]);
1370 {"start", cmd_start},
1372 {"restart", cmd_restart},
1373 {"reload", cmd_reload},
1375 {"purge", cmd_purge},
1376 {"debug", cmd_debug},
1377 {"retry", cmd_retry},
1378 {"connect", cmd_connect},
1379 {"disconnect", cmd_disconnect},
1384 {"config", cmd_config},
1386 {"generate-keys", cmd_generate_keys},
1387 {"generate-rsa-keys", cmd_generate_rsa_keys},
1388 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1390 {"version", cmd_version},
1396 int main(int argc, char *argv[]) {
1397 program_name = argv[0];
1399 if(!parse_options(argc, argv))
1414 if(optind >= argc) {
1415 fprintf(stderr, "No command given.\n");
1420 for(int i = 0; commands[i].command; i++) {
1421 if(!strcasecmp(argv[optind], commands[i].command))
1422 return commands[i].function(argc - optind, argv + optind);
1425 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);