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 controlcookie[1024];
52 char *confbase = NULL;
53 static char *tinc_conf = NULL;
54 static char *hosts_dir = NULL;
56 // Horrible global variables...
59 static char line[4096];
63 static bool force = false;
66 static struct WSAData wsa_state;
69 static struct option const long_options[] = {
70 {"config", required_argument, NULL, 'c'},
71 {"debug", optional_argument, NULL, 0},
72 {"no-detach", no_argument, NULL, 0},
73 {"mlock", no_argument, NULL, 0},
74 {"net", required_argument, NULL, 'n'},
75 {"help", no_argument, NULL, 1},
76 {"version", no_argument, NULL, 2},
77 {"pidfile", required_argument, NULL, 5},
78 {"logfile", required_argument, NULL, 0},
79 {"bypass-security", no_argument, NULL, 0},
80 {"chroot", no_argument, NULL, 0},
81 {"user", required_argument, NULL, 0},
82 {"option", required_argument, NULL, 0},
83 {"force", no_argument, NULL, 6},
87 static void version(void) {
88 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
89 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
90 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
91 "See the AUTHORS file for a complete list.\n\n"
92 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
93 "and you are welcome to redistribute it under certain conditions;\n"
94 "see the file COPYING for details.\n");
97 static void usage(bool status) {
99 fprintf(stderr, "Try `%s --help\' for more information.\n",
102 printf("Usage: %s [options] command\n\n", program_name);
103 printf("Valid options are:\n"
104 " -c, --config=DIR Read configuration options from DIR.\n"
105 " -n, --net=NETNAME Connect to net NETNAME.\n"
106 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
107 " --help Display this help and exit.\n"
108 " --version Output version information and exit.\n"
110 "Valid commands are:\n"
111 " init [name] Create initial configuration files.\n"
112 " config Change configuration:\n"
113 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
114 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
115 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
116 " start [tincd options] Start tincd.\n"
117 " stop Stop tincd.\n"
118 " restart Restart tincd.\n"
119 " reload Partially reload configuration of running tincd.\n"
120 " pid Show PID of currently running tincd.\n"
121 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
122 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
123 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
124 " dump Dump a list of one of the following things:\n"
125 " nodes - all known nodes in the VPN\n"
126 " edges - all known connections in the VPN\n"
127 " subnets - all known subnets in the VPN\n"
128 " connections - all meta connections with ourself\n"
129 " graph - graph of the VPN in dotty format\n"
130 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
131 " purge Purge unreachable nodes\n"
132 " debug N Set debug level\n"
133 " retry Retry all outgoing connections\n"
134 " disconnect NODE Close meta connection with NODE\n"
136 " top Show real-time statistics\n"
138 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
139 " log [level] Dump log output [up to the specified level]\n"
140 " export Export host configuration of local node to standard output\n"
141 " export-all Export all host configuration files to standard output\n"
142 " import [--force] Import host configuration file(s) from standard input\n"
144 printf("Report bugs to tinc@tinc-vpn.org.\n");
148 static bool parse_options(int argc, char **argv) {
150 int option_index = 0;
152 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
154 case 0: /* long option */
157 case 'c': /* config file */
158 confbase = xstrdup(optarg);
161 case 'n': /* net name given */
162 netname = xstrdup(optarg);
165 case 1: /* show help */
169 case 2: /* show version */
173 case 5: /* open control socket here */
174 pidfilename = xstrdup(optarg);
191 netname = getenv("NETNAME");
193 netname = xstrdup(netname);
199 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
205 /* Check stdin and stdout */
206 if(isatty(0) && isatty(1)) {
207 /* Ask for a file and/or directory name. */
208 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
212 if(fgets(buf, sizeof buf, stdin) == NULL) {
213 fprintf(stderr, "Error while reading stdin: %s\n",
218 size_t len = strlen(buf);
227 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
229 if(filename[0] != '/') {
231 /* The directory is a relative path or a filename. */
232 directory = get_current_dir_name();
233 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
237 umask(0077); /* Disallow everything for group and other */
239 /* Open it first to keep the inode busy */
241 r = fopen(filename, mode);
244 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
252 Generate a public/private ECDSA keypair, and ask for a file to store
255 static bool ecdsa_keygen() {
260 fprintf(stderr, "Generating ECDSA keypair:\n");
262 if(!ecdsa_generate(&key)) {
263 fprintf(stderr, "Error during key generation!\n");
266 fprintf(stderr, "Done.\n");
268 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
269 f = ask_and_open(filename, "private ECDSA key", "a");
275 /* Make it unreadable for others. */
276 fchmod(fileno(f), 0600);
280 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
282 ecdsa_write_pem_private_key(&key, f);
288 xasprintf(&filename, "%s/hosts/%s", confbase, name);
290 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
292 f = ask_and_open(filename, "public ECDSA key", "a");
298 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
300 char *pubkey = ecdsa_get_base64_public_key(&key);
301 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
311 Generate a public/private RSA keypair, and ask for a file to store
314 static bool rsa_keygen(int bits) {
319 fprintf(stderr, "Generating %d bits keys:\n", bits);
321 if(!rsa_generate(&key, bits, 0x10001)) {
322 fprintf(stderr, "Error during key generation!\n");
325 fprintf(stderr, "Done.\n");
327 xasprintf(&filename, "%s/rsa_key.priv", confbase);
328 f = ask_and_open(filename, "private RSA key", "a");
334 /* Make it unreadable for others. */
335 fchmod(fileno(f), 0600);
339 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
341 rsa_write_pem_private_key(&key, f);
347 xasprintf(&filename, "%s/hosts/%s", confbase, name);
349 xasprintf(&filename, "%s/rsa_key.pub", confbase);
351 f = ask_and_open(filename, "public RSA key", "a");
357 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
359 rsa_write_pem_public_key(&key, f);
368 Set all files and paths according to netname
370 static void make_names(void) {
373 char installdir[1024] = "";
374 long len = sizeof installdir;
378 xasprintf(&identname, "tinc.%s", netname);
380 identname = xstrdup("tinc");
383 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
384 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
387 xasprintf(&confbase, "%s/%s", installdir, netname);
389 xasprintf(&confbase, "%s", installdir);
393 xasprintf(&pidfilename, "%s/pid", confbase);
401 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
405 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
407 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
410 xasprintf(&confbase, CONFDIR "/tinc");
417 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
418 xasprintf(&hosts_dir, "%s/hosts", confbase);
421 static char buffer[4096];
422 static size_t blen = 0;
424 bool recvline(int fd, char *line, size_t len) {
425 char *newline = NULL;
427 while(!(newline = memchr(buffer, '\n', blen))) {
428 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
429 if(result == -1 && errno == EINTR)
436 if(newline - buffer >= len)
439 len = newline - buffer;
441 memcpy(line, buffer, len);
443 memmove(buffer, newline + 1, blen - len - 1);
449 static bool recvdata(int fd, char *data, size_t len) {
451 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
452 if(result == -1 && errno == EINTR)
459 memcpy(data, buffer, len);
460 memmove(buffer, buffer + len, blen - len);
466 bool sendline(int fd, char *format, ...) {
467 static char buffer[4096];
472 va_start(ap, format);
473 blen = vsnprintf(buffer, sizeof buffer, format, ap);
476 if(blen < 1 || blen >= sizeof buffer)
483 int result = send(fd, p, blen, 0);
484 if(result == -1 && errno == EINTR)
495 static void pcap(int fd, FILE *out, int snaplen) {
496 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
504 uint32_t tz_accuracy;
511 snaplen ?: sizeof data,
524 fwrite(&header, sizeof header, 1, out);
528 while(recvline(fd, line, sizeof line)) {
530 int n = sscanf(line, "%d %d %d", &code, &req, &len);
531 gettimeofday(&tv, NULL);
532 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
534 if(!recvdata(fd, data, len))
536 packet.tv_sec = tv.tv_sec;
537 packet.tv_usec = tv.tv_usec;
539 packet.origlen = len;
540 fwrite(&packet, sizeof packet, 1, out);
541 fwrite(data, len, 1, out);
546 static void logcontrol(int fd, FILE *out, int level) {
547 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
551 while(recvline(fd, line, sizeof line)) {
553 int n = sscanf(line, "%d %d %d", &code, &req, &len);
554 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
556 if(!recvdata(fd, data, len))
558 fwrite(data, len, 1, out);
565 static bool remove_service(void) {
566 SC_HANDLE manager = NULL;
567 SC_HANDLE service = NULL;
568 SERVICE_STATUS status = {0};
570 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
572 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
576 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
579 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
583 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
584 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
586 fprintf(stderr, "%s service stopped\n", identname);
588 if(!DeleteService(service)) {
589 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
593 fprintf(stderr, "%s service removed\n", identname);
599 static bool connect_tincd() {
603 FILE *f = fopen(pidfilename, "r");
605 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
612 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
613 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
618 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
619 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
624 struct addrinfo hints = {
625 .ai_family = AF_UNSPEC,
626 .ai_socktype = SOCK_STREAM,
627 .ai_protocol = IPPROTO_TCP,
631 struct addrinfo *res = NULL;
633 if(getaddrinfo(host, port, &hints, &res) || !res) {
634 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
638 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
640 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
645 unsigned long arg = 0;
647 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
648 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
652 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
653 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
662 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
663 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
667 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
669 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
670 fprintf(stderr, "Could not fully establish control socket connection\n");
678 static int cmd_start(int argc, char *argv[]) {
684 char *slash = strrchr(argv[0], '/');
687 if ((c = strrchr(argv[0], '\\')) > slash)
692 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
693 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
700 for(i = j = 1; argv[i]; ++i)
701 if (i != optind && strcmp(argv[i], "--") != 0)
706 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
710 static int cmd_stop(int argc, char *argv[]) {
715 sendline(fd, "%d %d", CONTROL, REQ_STOP);
716 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
717 fprintf(stderr, "Could not stop tinc daemon.\n");
721 if(!remove_service())
727 static int cmd_restart(int argc, char *argv[]) {
728 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
731 static int cmd_reload(int argc, char *argv[]) {
735 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
736 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
737 fprintf(stderr, "Could not reload configuration.\n");
745 static int cmd_dump(int argc, char *argv[]) {
747 fprintf(stderr, "Invalid number of arguments.\n");
755 bool do_graph = false;
757 if(!strcasecmp(argv[1], "nodes"))
758 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
759 else if(!strcasecmp(argv[1], "edges"))
760 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
761 else if(!strcasecmp(argv[1], "subnets"))
762 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
763 else if(!strcasecmp(argv[1], "connections"))
764 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
765 else if(!strcasecmp(argv[1], "graph")) {
766 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
767 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
770 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
776 printf("digraph {\n");
778 while(recvline(fd, line, sizeof line)) {
779 char node1[4096], node2[4096];
780 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
782 if(do_graph && req == REQ_DUMP_NODES)
794 printf("%s\n", line + 5);
796 if(req == REQ_DUMP_NODES)
797 printf(" %s [label = \"%s\"];\n", node1, node1);
799 printf(" %s -> %s;\n", node1, node2);
803 fprintf(stderr, "Error receiving dump.\n");
807 static int cmd_purge(int argc, char *argv[]) {
811 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
812 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
813 fprintf(stderr, "Could not purge old information.\n");
820 static int cmd_debug(int argc, char *argv[]) {
822 fprintf(stderr, "Invalid number of arguments.\n");
829 int debuglevel = atoi(argv[1]);
832 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
833 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
834 fprintf(stderr, "Could not set debug level.\n");
838 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
842 static int cmd_retry(int argc, char *argv[]) {
846 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
847 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
848 fprintf(stderr, "Could not retry outgoing connections.\n");
855 static int cmd_connect(int argc, char *argv[]) {
857 fprintf(stderr, "Invalid number of arguments.\n");
861 if(!check_id(argv[2])) {
862 fprintf(stderr, "Invalid name for node.\n");
869 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
870 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
871 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
878 static int cmd_disconnect(int argc, char *argv[]) {
880 fprintf(stderr, "Invalid number of arguments.\n");
884 if(!check_id(argv[2])) {
885 fprintf(stderr, "Invalid name for node.\n");
892 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
893 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
894 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
901 static int cmd_top(int argc, char *argv[]) {
909 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
914 static int cmd_pcap(int argc, char *argv[]) {
918 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
922 static int cmd_log(int argc, char *argv[]) {
926 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
930 static int cmd_pid(int argc, char *argv[]) {
938 static int rstrip(char *value) {
939 int len = strlen(value);
940 while(len && strchr("\t\r\n ", value[len - 1]))
945 static char *get_my_name() {
946 FILE *f = fopen(tinc_conf, "r");
948 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
954 while(fgets(buf, sizeof buf, f)) {
955 int len = strcspn(buf, "\t =");
957 value += strspn(value, "\t ");
960 value += strspn(value, "\t ");
965 if(strcasecmp(buf, "Name"))
969 return strdup(value);
974 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
978 static char *hostvariables[] = {
986 static int cmd_config(int argc, char *argv[]) {
988 fprintf(stderr, "Invalid number of arguments.\n");
993 if(!strcasecmp(argv[1], "add")) {
994 argv++, argc--, action = 1;
995 } else if(!strcasecmp(argv[1], "del")) {
996 argv++, argc--, action = -1;
997 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
998 argv++, argc--, action = 0;
1002 fprintf(stderr, "Invalid number of arguments.\n");
1006 // Concatenate the rest of the command line
1007 strncpy(line, argv[1], sizeof line - 1);
1008 for(int i = 2; i < argc; i++) {
1009 strncat(line, " ", sizeof line - 1 - strlen(line));
1010 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1013 // Liberal parsing into node name, variable name and value.
1019 len = strcspn(line, "\t =");
1021 value += strspn(value, "\t ");
1024 value += strspn(value, "\t ");
1027 variable = strchr(line, '.');
1036 fprintf(stderr, "No variable given.\n");
1040 if(action >= 0 && !*value) {
1041 fprintf(stderr, "No value for variable given.\n");
1045 // Should this go into our own host config file?
1047 for(int i = 0; hostvariables[i]; i++) {
1048 if(!strcasecmp(hostvariables[i], variable)) {
1049 node = get_my_name();
1057 if(node && !check_id(node)) {
1058 fprintf(stderr, "Invalid name for node.\n");
1062 // Open the right configuration file.
1065 xasprintf(&filename, "%s/%s", hosts_dir, node);
1067 filename = tinc_conf;
1069 FILE *f = fopen(filename, "r");
1071 if(action < 0 || errno != ENOENT) {
1072 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1076 // If it doesn't exist, create it.
1077 f = fopen(filename, "a+");
1079 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1082 fprintf(stderr, "Created configuration file %s.\n", filename);
1087 xasprintf(&tmpfile, "%s.config.tmp", filename);
1088 FILE *tf = fopen(tmpfile, "w");
1090 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1094 // Copy the file, making modifications on the fly.
1098 bool removed = false;
1100 while(fgets(buf1, sizeof buf1, f)) {
1101 buf1[sizeof buf1 - 1] = 0;
1104 // Parse line in a simple way
1108 len = strcspn(buf2, "\t =");
1109 bvalue = buf2 + len;
1110 bvalue += strspn(bvalue, "\t ");
1111 if(*bvalue == '=') {
1113 bvalue += strspn(bvalue, "\t ");
1119 if(!strcasecmp(buf2, variable)) {
1122 if(!*value || !strcasecmp(bvalue, value)) {
1127 } else if(action == 0) {
1128 // Already set? Delete the rest...
1131 // Otherwise, replace.
1132 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1133 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1141 // Copy original line...
1142 if(fputs(buf1, tf) < 0) {
1143 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1148 // Make sure we read everything...
1149 if(ferror(f) || !feof(f)) {
1150 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1155 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1159 // Add new variable if necessary.
1160 if(action > 0 || (action == 0 && !set)) {
1161 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1162 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1167 // Make sure we wrote everything...
1169 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1173 // Could we find what we had to remove?
1174 if(action < 0 && !removed) {
1176 fprintf(stderr, "No configuration variables deleted.\n");
1180 // Replace the configuration file with the new one
1182 if(remove(filename)) {
1183 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1187 if(rename(tmpfile, filename)) {
1188 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1192 // Silently try notifying a running tincd of changes.
1196 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1201 bool check_id(const char *name) {
1202 for(int i = 0; i < strlen(name); i++) {
1203 if(!isalnum(name[i]) && name[i] != '_')
1210 static int cmd_init(int argc, char *argv[]) {
1211 if(!access(tinc_conf, F_OK)) {
1212 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1217 if(isatty(0) && isatty(1)) {
1219 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1221 if(!fgets(buf, sizeof buf, stdin)) {
1222 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1225 int len = rstrip(buf);
1227 fprintf(stderr, "No name given!\n");
1232 fprintf(stderr, "No Name given!\n");
1236 name = strdup(argv[1]);
1238 fprintf(stderr, "No Name given!\n");
1243 if(!check_id(name)) {
1244 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1248 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1249 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1253 if(mkdir(confbase, 0755) && errno != EEXIST) {
1254 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1258 char *hosts_dir = NULL;
1259 xasprintf(&hosts_dir, "%s/hosts", confbase);
1260 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1261 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1265 FILE *f = fopen(tinc_conf, "w");
1267 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1271 fprintf(f, "Name = %s\n", name);
1275 if(!rsa_keygen(2048) || !ecdsa_keygen())
1282 static int cmd_generate_keys(int argc, char *argv[]) {
1283 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1286 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1287 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1290 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1291 return !ecdsa_keygen();
1294 static int cmd_help(int argc, char *argv[]) {
1299 static int cmd_version(int argc, char *argv[]) {
1304 static int cmd_info(int argc, char *argv[]) {
1306 fprintf(stderr, "Invalid number of arguments.\n");
1310 if(!connect_tincd())
1313 return info(fd, argv[1]);
1316 static const char *conffiles[] = {
1327 static int cmd_edit(int argc, char *argv[]) {
1329 fprintf(stderr, "Invalid number of arguments.\n");
1333 char *filename = NULL;
1335 if(strncmp(argv[1], "hosts/", 6)) {
1336 for(int i = 0; conffiles[i]; i++) {
1337 if(!strcmp(argv[1], conffiles[i])) {
1338 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1347 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1348 char *dash = strchr(argv[1], '-');
1351 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1352 fprintf(stderr, "Invalid configuration filename.\n");
1359 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1361 char *editor = "edit";
1365 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1366 int result = system(command);
1370 // Silently try notifying a running tincd of changes.
1374 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1379 static int export(const char *name, FILE *out) {
1381 xasprintf(&filename, "%s/%s", hosts_dir, name);
1382 FILE *in = fopen(filename, "r");
1384 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1388 fprintf(out, "Name = %s\n", name);
1390 while(fgets(buf, sizeof buf, in)) {
1391 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1396 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1404 static int cmd_export(int argc, char *argv[]) {
1405 char *name = get_my_name();
1409 return export(name, stdout);
1412 static int cmd_export_all(int argc, char *argv[]) {
1413 DIR *dir = opendir(hosts_dir);
1415 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1423 while((ent = readdir(dir))) {
1424 if(!check_id(ent->d_name))
1430 printf("#---------------------------------------------------------------#\n");
1432 result |= export(ent->d_name, stdout);
1439 static int cmd_import(int argc, char *argv[]) {
1447 bool firstline = true;
1449 while(fgets(buf, sizeof buf, in)) {
1450 if(sscanf(buf, "Name = %s", name) == 1) {
1451 if(!check_id(name)) {
1452 fprintf(stderr, "Invalid Name in input!\n");
1460 xasprintf(&filename, "%s/%s", hosts_dir, name);
1462 if(!force && !access(filename, F_OK)) {
1463 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1468 out = fopen(filename, "w");
1470 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1477 } else if(firstline) {
1478 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1483 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1487 if(fputs(buf, out) < 0) {
1488 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1498 fprintf(stderr, "Imported %d host configuration files.\n", count);
1501 fprintf(stderr, "No host configuration files imported.\n");
1506 static const struct {
1507 const char *command;
1508 int (*function)(int argc, char *argv[]);
1510 {"start", cmd_start},
1512 {"restart", cmd_restart},
1513 {"reload", cmd_reload},
1515 {"purge", cmd_purge},
1516 {"debug", cmd_debug},
1517 {"retry", cmd_retry},
1518 {"connect", cmd_connect},
1519 {"disconnect", cmd_disconnect},
1524 {"config", cmd_config},
1526 {"generate-keys", cmd_generate_keys},
1527 {"generate-rsa-keys", cmd_generate_rsa_keys},
1528 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1530 {"version", cmd_version},
1533 {"export", cmd_export},
1534 {"export-all", cmd_export_all},
1535 {"import", cmd_import},
1539 int main(int argc, char *argv[]) {
1540 program_name = argv[0];
1542 if(!parse_options(argc, argv))
1557 if(optind >= argc) {
1558 fprintf(stderr, "No command given.\n");
1563 for(int i = 0; commands[i].command; i++) {
1564 if(!strcasecmp(argv[optind], commands[i].command))
1565 return commands[i].function(argc - optind, argv + optind);
1568 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);