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 {"net", required_argument, NULL, 'n'},
66 {"help", no_argument, NULL, 1},
67 {"version", no_argument, NULL, 2},
68 {"pidfile", required_argument, NULL, 5},
72 static void version(void) {
73 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
74 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
75 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
76 "See the AUTHORS file for a complete list.\n\n"
77 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
78 "and you are welcome to redistribute it under certain conditions;\n"
79 "see the file COPYING for details.\n");
82 static void usage(bool status) {
84 fprintf(stderr, "Try `%s --help\' for more information.\n",
87 printf("Usage: %s [options] command\n\n", program_name);
88 printf("Valid options are:\n"
89 " -c, --config=DIR Read configuration options from DIR.\n"
90 " -n, --net=NETNAME Connect to net NETNAME.\n"
91 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
92 " --help Display this help and exit.\n"
93 " --version Output version information and exit.\n"
95 "Valid commands are:\n"
96 " init [name] Create initial configuration files.\n"
97 " config Change configuration:\n"
98 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
99 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
100 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
101 " start Start tincd.\n"
102 " stop Stop tincd.\n"
103 " restart Restart tincd.\n"
104 " reload Partially reload configuration of running tincd.\n"
105 " pid Show PID of currently running tincd.\n"
106 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
107 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
108 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
109 " dump Dump a list of one of the following things:\n"
110 " nodes - all known nodes in the VPN\n"
111 " edges - all known connections in the VPN\n"
112 " subnets - all known subnets in the VPN\n"
113 " connections - all meta connections with ourself\n"
114 " graph - graph of the VPN in dotty format\n"
115 " purge Purge unreachable nodes\n"
116 " debug N Set debug level\n"
117 " retry Retry all outgoing connections\n"
118 " disconnect NODE Close meta connection with NODE\n"
120 " top Show real-time statistics\n"
122 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
123 " log [level] Dump log output [up to the specified level]\n"
125 printf("Report bugs to tinc@tinc-vpn.org.\n");
129 static bool parse_options(int argc, char **argv) {
131 int option_index = 0;
133 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
135 case 0: /* long option */
138 case 'c': /* config file */
139 confbase = xstrdup(optarg);
142 case 'n': /* net name given */
143 netname = xstrdup(optarg);
146 case 1: /* show help */
150 case 2: /* show version */
154 case 5: /* open control socket here */
155 pidfilename = xstrdup(optarg);
168 netname = getenv("NETNAME");
170 netname = xstrdup(netname);
176 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
182 /* Check stdin and stdout */
183 if(isatty(0) && isatty(1)) {
184 /* Ask for a file and/or directory name. */
185 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
189 if(fgets(buf, sizeof buf, stdin) == NULL) {
190 fprintf(stderr, "Error while reading stdin: %s\n",
195 size_t len = strlen(buf);
204 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
206 if(filename[0] != '/') {
208 /* The directory is a relative path or a filename. */
209 directory = get_current_dir_name();
210 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
214 umask(0077); /* Disallow everything for group and other */
216 /* Open it first to keep the inode busy */
218 r = fopen(filename, mode);
221 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
229 Generate a public/private ECDSA keypair, and ask for a file to store
232 static bool ecdsa_keygen() {
237 fprintf(stderr, "Generating ECDSA keypair:\n");
239 if(!ecdsa_generate(&key)) {
240 fprintf(stderr, "Error during key generation!\n");
243 fprintf(stderr, "Done.\n");
245 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
246 f = ask_and_open(filename, "private ECDSA key", "a");
252 /* Make it unreadable for others. */
253 fchmod(fileno(f), 0600);
257 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
259 ecdsa_write_pem_private_key(&key, f);
265 xasprintf(&filename, "%s/hosts/%s", confbase, name);
267 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
269 f = ask_and_open(filename, "public ECDSA key", "a");
275 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
277 char *pubkey = ecdsa_get_base64_public_key(&key);
278 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
288 Generate a public/private RSA keypair, and ask for a file to store
291 static bool rsa_keygen(int bits) {
296 fprintf(stderr, "Generating %d bits keys:\n", bits);
298 if(!rsa_generate(&key, bits, 0x10001)) {
299 fprintf(stderr, "Error during key generation!\n");
302 fprintf(stderr, "Done.\n");
304 xasprintf(&filename, "%s/rsa_key.priv", confbase);
305 f = ask_and_open(filename, "private RSA key", "a");
311 /* Make it unreadable for others. */
312 fchmod(fileno(f), 0600);
316 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
318 rsa_write_pem_private_key(&key, f);
324 xasprintf(&filename, "%s/hosts/%s", confbase, name);
326 xasprintf(&filename, "%s/rsa_key.pub", confbase);
328 f = ask_and_open(filename, "public RSA key", "a");
334 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
336 rsa_write_pem_public_key(&key, f);
345 Set all files and paths according to netname
347 static void make_names(void) {
350 char installdir[1024] = "";
351 long len = sizeof installdir;
355 xasprintf(&identname, "tinc.%s", netname);
357 identname = xstrdup("tinc");
360 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
361 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
364 xasprintf(&confbase, "%s/%s", installdir, netname);
366 xasprintf(&confbase, "%s", installdir);
370 xasprintf(&pidfilename, "%s/pid", confbase);
378 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
382 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
384 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
387 xasprintf(&confbase, CONFDIR "/tinc");
394 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
395 xasprintf(&hosts_dir, "%s/hosts", confbase);
398 static char buffer[4096];
399 static size_t blen = 0;
401 bool recvline(int fd, char *line, size_t len) {
402 char *newline = NULL;
404 while(!(newline = memchr(buffer, '\n', blen))) {
405 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
406 if(result == -1 && errno == EINTR)
413 if(newline - buffer >= len)
416 len = newline - buffer;
418 memcpy(line, buffer, len);
420 memmove(buffer, newline + 1, blen - len - 1);
426 static bool recvdata(int fd, char *data, size_t len) {
428 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
429 if(result == -1 && errno == EINTR)
436 memcpy(data, buffer, len);
437 memmove(buffer, buffer + len, blen - len);
443 bool sendline(int fd, char *format, ...) {
444 static char buffer[4096];
449 va_start(ap, format);
450 blen = vsnprintf(buffer, sizeof buffer, format, ap);
453 if(blen < 1 || blen >= sizeof buffer)
460 int result = send(fd, p, blen, 0);
461 if(result == -1 && errno == EINTR)
472 static void pcap(int fd, FILE *out, int snaplen) {
473 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
481 uint32_t tz_accuracy;
488 snaplen ?: sizeof data,
501 fwrite(&header, sizeof header, 1, out);
505 while(recvline(fd, line, sizeof line)) {
507 int n = sscanf(line, "%d %d %d", &code, &req, &len);
508 gettimeofday(&tv, NULL);
509 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
511 if(!recvdata(fd, data, len))
513 packet.tv_sec = tv.tv_sec;
514 packet.tv_usec = tv.tv_usec;
516 packet.origlen = len;
517 fwrite(&packet, sizeof packet, 1, out);
518 fwrite(data, len, 1, out);
523 static void logcontrol(int fd, FILE *out, int level) {
524 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
528 while(recvline(fd, line, sizeof line)) {
530 int n = sscanf(line, "%d %d %d", &code, &req, &len);
531 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
533 if(!recvdata(fd, data, len))
535 fwrite(data, len, 1, out);
542 static bool remove_service(void) {
543 SC_HANDLE manager = NULL;
544 SC_HANDLE service = NULL;
545 SERVICE_STATUS status = {0};
547 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
549 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
553 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
556 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
560 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
561 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
563 fprintf(stderr, "%s service stopped\n", identname);
565 if(!DeleteService(service)) {
566 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
570 fprintf(stderr, "%s service removed\n", identname);
576 static bool connect_tincd() {
580 FILE *f = fopen(pidfilename, "r");
582 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
589 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
590 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
595 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
596 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
601 struct addrinfo hints = {
602 .ai_family = AF_UNSPEC,
603 .ai_socktype = SOCK_STREAM,
604 .ai_protocol = IPPROTO_TCP,
608 struct addrinfo *res = NULL;
610 if(getaddrinfo(host, port, &hints, &res) || !res) {
611 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
615 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
617 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
622 unsigned long arg = 0;
624 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
625 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
629 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
630 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
639 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
640 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
644 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
646 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
647 fprintf(stderr, "Could not fully establish control socket connection\n");
655 static int cmd_start(int argc, char *argv[]) {
658 char *slash = strrchr(argv[0], '/');
661 if ((c = strrchr(argv[0], '\\')) > slash)
666 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
667 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
674 for(i = j = 1; argv[i]; ++i)
675 if (i != optind && strcmp(argv[i], "--") != 0)
680 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
684 static int cmd_stop(int argc, char *argv[]) {
689 sendline(fd, "%d %d", CONTROL, REQ_STOP);
690 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
691 fprintf(stderr, "Could not stop tinc daemon.\n");
695 if(!remove_service())
701 static int cmd_restart(int argc, char *argv[]) {
702 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
705 static int cmd_reload(int argc, char *argv[]) {
709 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
710 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
711 fprintf(stderr, "Could not reload configuration.\n");
719 static int cmd_dump(int argc, char *argv[]) {
721 fprintf(stderr, "Invalid number of arguments.\n");
726 bool do_graph = false;
728 if(!strcasecmp(argv[1], "nodes"))
729 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
730 else if(!strcasecmp(argv[1], "edges"))
731 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
732 else if(!strcasecmp(argv[1], "subnets"))
733 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
734 else if(!strcasecmp(argv[1], "connections"))
735 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
736 else if(!strcasecmp(argv[1], "graph")) {
737 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
738 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
741 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
750 printf("digraph {\n");
752 while(recvline(fd, line, sizeof line)) {
753 char node1[4096], node2[4096];
754 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
756 if(do_graph && req == REQ_DUMP_NODES)
768 printf("%s\n", line + 5);
770 if(req == REQ_DUMP_NODES)
771 printf(" %s [label = \"%s\"];\n", node1, node1);
773 printf(" %s -> %s;\n", node1, node2);
777 fprintf(stderr, "Error receiving dump.\n");
781 static int cmd_purge(int argc, char *argv[]) {
785 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
786 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
787 fprintf(stderr, "Could not purge old information.\n");
794 static int cmd_debug(int argc, char *argv[]) {
796 fprintf(stderr, "Invalid number of arguments.\n");
803 int debuglevel = atoi(argv[1]);
806 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
807 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
808 fprintf(stderr, "Could not set debug level.\n");
812 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
816 static int cmd_retry(int argc, char *argv[]) {
820 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
821 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
822 fprintf(stderr, "Could not retry outgoing connections.\n");
829 static int cmd_connect(int argc, char *argv[]) {
831 fprintf(stderr, "Invalid number of arguments.\n");
835 if(!check_id(argv[2])) {
836 fprintf(stderr, "Invalid name for node.\n");
843 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
844 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
845 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
852 static int cmd_disconnect(int argc, char *argv[]) {
854 fprintf(stderr, "Invalid number of arguments.\n");
858 if(!check_id(argv[2])) {
859 fprintf(stderr, "Invalid name for node.\n");
866 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
867 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
868 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
875 static int cmd_top(int argc, char *argv[]) {
883 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
888 static int cmd_pcap(int argc, char *argv[]) {
892 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
896 static int cmd_log(int argc, char *argv[]) {
900 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
904 static int cmd_pid(int argc, char *argv[]) {
912 static int rstrip(char *value) {
913 int len = strlen(value);
914 while(len && strchr("\t\r\n ", value[len - 1]))
919 static char *get_my_name() {
920 FILE *f = fopen(tinc_conf, "r");
922 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
928 while(fgets(buf, sizeof buf, f)) {
929 int len = strcspn(buf, "\t =");
931 value += strspn(value, "\t ");
934 value += strspn(value, "\t ");
939 if(strcasecmp(buf, "Name"))
943 return strdup(value);
948 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
952 static char *hostvariables[] = {
960 static int cmd_config(int argc, char *argv[]) {
962 fprintf(stderr, "Invalid number of arguments.\n");
967 if(!strcasecmp(argv[1], "add")) {
968 argv++, argc--, action = 1;
969 } else if(!strcasecmp(argv[1], "del")) {
970 argv++, argc--, action = -1;
971 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
972 argv++, argc--, action = 0;
976 fprintf(stderr, "Invalid number of arguments.\n");
980 // Concatenate the rest of the command line
981 strncpy(line, argv[1], sizeof line - 1);
982 for(int i = 2; i < argc; i++) {
983 strncat(line, " ", sizeof line - 1 - strlen(line));
984 strncat(line, argv[i], sizeof line - 1 - strlen(line));
987 // Liberal parsing into node name, variable name and value.
993 len = strcspn(line, "\t =");
995 value += strspn(value, "\t ");
998 value += strspn(value, "\t ");
1001 variable = strchr(line, '.');
1010 fprintf(stderr, "No variable given.\n");
1014 if(action >= 0 && !*value) {
1015 fprintf(stderr, "No value for variable given.\n");
1019 // Should this go into our own host config file?
1021 for(int i = 0; hostvariables[i]; i++) {
1022 if(!strcasecmp(hostvariables[i], variable)) {
1023 node = get_my_name();
1031 if(node && !check_id(node)) {
1032 fprintf(stderr, "Invalid name for node.\n");
1036 // Open the right configuration file.
1039 xasprintf(&filename, "%s/%s", hosts_dir, node);
1041 filename = tinc_conf;
1043 FILE *f = fopen(filename, "r");
1045 if(action < 0 || errno != ENOENT) {
1046 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1050 // If it doesn't exist, create it.
1051 f = fopen(filename, "a+");
1053 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1056 fprintf(stderr, "Created configuration file %s.\n", filename);
1061 xasprintf(&tmpfile, "%s.config.tmp", filename);
1062 FILE *tf = fopen(tmpfile, "w");
1064 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1068 // Copy the file, making modifications on the fly.
1072 bool removed = false;
1074 while(fgets(buf1, sizeof buf1, f)) {
1075 buf1[sizeof buf1 - 1] = 0;
1078 // Parse line in a simple way
1082 len = strcspn(buf2, "\t =");
1083 bvalue = buf2 + len;
1084 bvalue += strspn(bvalue, "\t ");
1085 if(*bvalue == '=') {
1087 bvalue += strspn(bvalue, "\t ");
1093 if(!strcasecmp(buf2, variable)) {
1096 if(!*value || !strcasecmp(bvalue, value)) {
1101 } else if(action == 0) {
1102 // Already set? Delete the rest...
1105 // Otherwise, replace.
1106 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1107 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1115 // Copy original line...
1116 if(fputs(buf1, tf) < 0) {
1117 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1122 // Make sure we read everything...
1123 if(ferror(f) || !feof(f)) {
1124 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1129 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1133 // Add new variable if necessary.
1134 if(action > 0 || (action == 0 && !set)) {
1135 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1136 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1141 // Make sure we wrote everything...
1143 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1147 // Could we find what we had to remove?
1148 if(action < 0 && !removed) {
1150 fprintf(stderr, "No configuration variables deleted.\n");
1154 // Replace the configuration file with the new one
1156 if(remove(filename)) {
1157 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1161 if(rename(tmpfile, filename)) {
1162 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1166 // Silently try notifying a running tincd of changes.
1170 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1175 bool check_id(const char *name) {
1176 for(int i = 0; i < strlen(name); i++) {
1177 if(!isalnum(name[i]) && name[i] != '_')
1184 static int cmd_init(int argc, char *argv[]) {
1185 if(!access(tinc_conf, F_OK)) {
1186 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1191 if(isatty(0) && isatty(1)) {
1193 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1195 if(!fgets(buf, sizeof buf, stdin)) {
1196 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1199 int len = rstrip(buf);
1201 fprintf(stderr, "No name given!\n");
1206 fprintf(stderr, "No Name given!\n");
1210 name = strdup(argv[1]);
1212 fprintf(stderr, "No Name given!\n");
1217 if(!check_id(name)) {
1218 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1222 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1223 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1227 if(mkdir(confbase, 0755) && errno != EEXIST) {
1228 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1232 char *hosts_dir = NULL;
1233 xasprintf(&hosts_dir, "%s/hosts", confbase);
1234 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1235 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1239 FILE *f = fopen(tinc_conf, "w");
1241 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1245 fprintf(f, "Name = %s\n", name);
1249 if(!rsa_keygen(2048) || !ecdsa_keygen())
1256 static int cmd_generate_keys(int argc, char *argv[]) {
1257 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1260 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1261 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1264 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1265 return !ecdsa_keygen();
1268 static int cmd_help(int argc, char *argv[]) {
1273 static int cmd_version(int argc, char *argv[]) {
1278 static const char *conffiles[] = {
1289 static int cmd_edit(int argc, char *argv[]) {
1291 fprintf(stderr, "Invalid number of arguments.\n");
1295 char *filename = NULL;
1297 if(strncmp(argv[1], "hosts/", 6)) {
1298 for(int i = 0; conffiles[i]; i++) {
1299 if(!strcmp(argv[1], conffiles[i])) {
1300 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1309 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1310 char *dash = strchr(argv[1], '-');
1313 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1314 fprintf(stderr, "Invalid configuration filename.\n");
1321 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1323 char *editor = "edit"
1327 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1328 int result = system(command);
1332 // Silently try notifying a running tincd of changes.
1336 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1341 static const struct {
1342 const char *command;
1343 int (*function)(int argc, char *argv[]);
1345 {"start", cmd_start},
1347 {"restart", cmd_restart},
1348 {"reload", cmd_reload},
1350 {"purge", cmd_purge},
1351 {"debug", cmd_debug},
1352 {"retry", cmd_retry},
1353 {"connect", cmd_connect},
1354 {"disconnect", cmd_disconnect},
1359 {"config", cmd_config},
1361 {"generate-keys", cmd_generate_keys},
1362 {"generate-rsa-keys", cmd_generate_rsa_keys},
1363 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1365 {"version", cmd_version},
1370 int main(int argc, char *argv[]) {
1371 program_name = argv[0];
1373 if(!parse_options(argc, argv))
1388 if(optind >= argc) {
1389 fprintf(stderr, "No command given.\n");
1394 for(int i = 0; commands[i].command; i++) {
1395 if(!strcasecmp(argv[optind], commands[i].command))
1396 return commands[i].function(argc - optind, argv + optind);
1399 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);