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];
59 static bool force = false;
62 static struct WSAData wsa_state;
65 static struct option const long_options[] = {
66 {"config", required_argument, NULL, 'c'},
67 {"debug", optional_argument, NULL, 0},
68 {"no-detach", no_argument, NULL, 0},
69 {"mlock", no_argument, NULL, 0},
70 {"net", required_argument, NULL, 'n'},
71 {"help", no_argument, NULL, 1},
72 {"version", no_argument, NULL, 2},
73 {"pidfile", required_argument, NULL, 5},
74 {"logfile", required_argument, NULL, 0},
75 {"bypass-security", no_argument, NULL, 0},
76 {"chroot", no_argument, NULL, 0},
77 {"user", required_argument, NULL, 0},
78 {"option", required_argument, NULL, 0},
79 {"force", no_argument, NULL, 6},
83 static void version(void) {
84 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
85 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
86 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
87 "See the AUTHORS file for a complete list.\n\n"
88 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
89 "and you are welcome to redistribute it under certain conditions;\n"
90 "see the file COPYING for details.\n");
93 static void usage(bool status) {
95 fprintf(stderr, "Try `%s --help\' for more information.\n",
98 printf("Usage: %s [options] command\n\n", program_name);
99 printf("Valid options are:\n"
100 " -c, --config=DIR Read configuration options from DIR.\n"
101 " -n, --net=NETNAME Connect to net NETNAME.\n"
102 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
103 " --help Display this help and exit.\n"
104 " --version Output version information and exit.\n"
106 "Valid commands are:\n"
107 " init [name] Create initial configuration files.\n"
108 " config Change configuration:\n"
109 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
110 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
111 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
112 " start [tincd options] Start tincd.\n"
113 " stop Stop tincd.\n"
114 " restart Restart tincd.\n"
115 " reload Partially reload configuration of running tincd.\n"
116 " pid Show PID of currently running tincd.\n"
117 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
118 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
119 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
120 " dump Dump a list of one of the following things:\n"
121 " nodes - all known nodes in the VPN\n"
122 " edges - all known connections in the VPN\n"
123 " subnets - all known subnets in the VPN\n"
124 " connections - all meta connections with ourself\n"
125 " graph - graph of the VPN in dotty format\n"
126 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
127 " purge Purge unreachable nodes\n"
128 " debug N Set debug level\n"
129 " retry Retry all outgoing connections\n"
130 " disconnect NODE Close meta connection with NODE\n"
132 " top Show real-time statistics\n"
134 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
135 " log [level] Dump log output [up to the specified level]\n"
136 " export Export host configuration of local node to standard output\n"
137 " export-all Export all host configuration files to standard output\n"
138 " import [--force] Import host configuration file(s) from standard input\n"
140 printf("Report bugs to tinc@tinc-vpn.org.\n");
144 static bool parse_options(int argc, char **argv) {
146 int option_index = 0;
148 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
150 case 0: /* long option */
153 case 'c': /* config file */
154 confbase = xstrdup(optarg);
157 case 'n': /* net name given */
158 netname = xstrdup(optarg);
161 case 1: /* show help */
165 case 2: /* show version */
169 case 5: /* open control socket here */
170 pidfilename = xstrdup(optarg);
187 netname = getenv("NETNAME");
189 netname = xstrdup(netname);
195 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
201 /* Check stdin and stdout */
202 if(isatty(0) && isatty(1)) {
203 /* Ask for a file and/or directory name. */
204 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
208 if(fgets(buf, sizeof buf, stdin) == NULL) {
209 fprintf(stderr, "Error while reading stdin: %s\n",
214 size_t len = strlen(buf);
223 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
225 if(filename[0] != '/') {
227 /* The directory is a relative path or a filename. */
228 directory = get_current_dir_name();
229 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
233 umask(0077); /* Disallow everything for group and other */
235 /* Open it first to keep the inode busy */
237 r = fopen(filename, mode);
240 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
248 Generate a public/private ECDSA keypair, and ask for a file to store
251 static bool ecdsa_keygen() {
256 fprintf(stderr, "Generating ECDSA keypair:\n");
258 if(!ecdsa_generate(&key)) {
259 fprintf(stderr, "Error during key generation!\n");
262 fprintf(stderr, "Done.\n");
264 xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
265 f = ask_and_open(filename, "private ECDSA key", "a");
271 /* Make it unreadable for others. */
272 fchmod(fileno(f), 0600);
276 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
278 ecdsa_write_pem_private_key(&key, f);
284 xasprintf(&filename, "%s/hosts/%s", confbase, name);
286 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
288 f = ask_and_open(filename, "public ECDSA key", "a");
294 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
296 char *pubkey = ecdsa_get_base64_public_key(&key);
297 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
307 Generate a public/private RSA keypair, and ask for a file to store
310 static bool rsa_keygen(int bits) {
315 fprintf(stderr, "Generating %d bits keys:\n", bits);
317 if(!rsa_generate(&key, bits, 0x10001)) {
318 fprintf(stderr, "Error during key generation!\n");
321 fprintf(stderr, "Done.\n");
323 xasprintf(&filename, "%s/rsa_key.priv", confbase);
324 f = ask_and_open(filename, "private RSA key", "a");
330 /* Make it unreadable for others. */
331 fchmod(fileno(f), 0600);
335 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
337 rsa_write_pem_private_key(&key, f);
343 xasprintf(&filename, "%s/hosts/%s", confbase, name);
345 xasprintf(&filename, "%s/rsa_key.pub", confbase);
347 f = ask_and_open(filename, "public RSA key", "a");
353 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
355 rsa_write_pem_public_key(&key, f);
364 Set all files and paths according to netname
366 static void make_names(void) {
369 char installdir[1024] = "";
370 long len = sizeof installdir;
374 xasprintf(&identname, "tinc.%s", netname);
376 identname = xstrdup("tinc");
379 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
380 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
383 xasprintf(&confbase, "%s/%s", installdir, netname);
385 xasprintf(&confbase, "%s", installdir);
389 xasprintf(&pidfilename, "%s/pid", confbase);
397 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
401 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
403 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
406 xasprintf(&confbase, CONFDIR "/tinc");
413 xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
414 xasprintf(&hosts_dir, "%s/hosts", confbase);
417 static char buffer[4096];
418 static size_t blen = 0;
420 bool recvline(int fd, char *line, size_t len) {
421 char *newline = NULL;
423 while(!(newline = memchr(buffer, '\n', blen))) {
424 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
425 if(result == -1 && errno == EINTR)
432 if(newline - buffer >= len)
435 len = newline - buffer;
437 memcpy(line, buffer, len);
439 memmove(buffer, newline + 1, blen - len - 1);
445 static bool recvdata(int fd, char *data, size_t len) {
447 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
448 if(result == -1 && errno == EINTR)
455 memcpy(data, buffer, len);
456 memmove(buffer, buffer + len, blen - len);
462 bool sendline(int fd, char *format, ...) {
463 static char buffer[4096];
468 va_start(ap, format);
469 blen = vsnprintf(buffer, sizeof buffer, format, ap);
472 if(blen < 1 || blen >= sizeof buffer)
479 int result = send(fd, p, blen, 0);
480 if(result == -1 && errno == EINTR)
491 static void pcap(int fd, FILE *out, int snaplen) {
492 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
500 uint32_t tz_accuracy;
507 snaplen ?: sizeof data,
520 fwrite(&header, sizeof header, 1, out);
524 while(recvline(fd, line, sizeof line)) {
526 int n = sscanf(line, "%d %d %d", &code, &req, &len);
527 gettimeofday(&tv, NULL);
528 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
530 if(!recvdata(fd, data, len))
532 packet.tv_sec = tv.tv_sec;
533 packet.tv_usec = tv.tv_usec;
535 packet.origlen = len;
536 fwrite(&packet, sizeof packet, 1, out);
537 fwrite(data, len, 1, out);
542 static void logcontrol(int fd, FILE *out, int level) {
543 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
547 while(recvline(fd, line, sizeof line)) {
549 int n = sscanf(line, "%d %d %d", &code, &req, &len);
550 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
552 if(!recvdata(fd, data, len))
554 fwrite(data, len, 1, out);
561 static bool remove_service(void) {
562 SC_HANDLE manager = NULL;
563 SC_HANDLE service = NULL;
564 SERVICE_STATUS status = {0};
566 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
568 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
572 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
575 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
579 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
580 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
582 fprintf(stderr, "%s service stopped\n", identname);
584 if(!DeleteService(service)) {
585 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
589 fprintf(stderr, "%s service removed\n", identname);
595 static bool connect_tincd() {
599 FILE *f = fopen(pidfilename, "r");
601 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
608 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
609 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
614 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
615 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
620 struct addrinfo hints = {
621 .ai_family = AF_UNSPEC,
622 .ai_socktype = SOCK_STREAM,
623 .ai_protocol = IPPROTO_TCP,
627 struct addrinfo *res = NULL;
629 if(getaddrinfo(host, port, &hints, &res) || !res) {
630 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
634 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
636 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
641 unsigned long arg = 0;
643 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
644 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
648 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
649 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
658 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
659 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
663 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
665 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
666 fprintf(stderr, "Could not fully establish control socket connection\n");
674 static int cmd_start(int argc, char *argv[]) {
680 char *slash = strrchr(argv[0], '/');
683 if ((c = strrchr(argv[0], '\\')) > slash)
688 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
689 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
696 for(i = j = 1; argv[i]; ++i)
697 if (i != optind && strcmp(argv[i], "--") != 0)
702 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
706 static int cmd_stop(int argc, char *argv[]) {
711 sendline(fd, "%d %d", CONTROL, REQ_STOP);
712 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
713 fprintf(stderr, "Could not stop tinc daemon.\n");
717 if(!remove_service())
723 static int cmd_restart(int argc, char *argv[]) {
724 return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
727 static int cmd_reload(int argc, char *argv[]) {
731 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
732 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
733 fprintf(stderr, "Could not reload configuration.\n");
741 static int cmd_dump(int argc, char *argv[]) {
743 fprintf(stderr, "Invalid number of arguments.\n");
751 bool do_graph = false;
753 if(!strcasecmp(argv[1], "nodes"))
754 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
755 else if(!strcasecmp(argv[1], "edges"))
756 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
757 else if(!strcasecmp(argv[1], "subnets"))
758 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
759 else if(!strcasecmp(argv[1], "connections"))
760 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
761 else if(!strcasecmp(argv[1], "graph")) {
762 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
763 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
766 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
772 printf("digraph {\n");
774 while(recvline(fd, line, sizeof line)) {
775 char node1[4096], node2[4096];
776 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
778 if(do_graph && req == REQ_DUMP_NODES)
790 printf("%s\n", line + 5);
792 if(req == REQ_DUMP_NODES)
793 printf(" %s [label = \"%s\"];\n", node1, node1);
795 printf(" %s -> %s;\n", node1, node2);
799 fprintf(stderr, "Error receiving dump.\n");
803 static int cmd_purge(int argc, char *argv[]) {
807 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
808 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
809 fprintf(stderr, "Could not purge old information.\n");
816 static int cmd_debug(int argc, char *argv[]) {
818 fprintf(stderr, "Invalid number of arguments.\n");
825 int debuglevel = atoi(argv[1]);
828 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
829 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
830 fprintf(stderr, "Could not set debug level.\n");
834 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
838 static int cmd_retry(int argc, char *argv[]) {
842 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
843 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
844 fprintf(stderr, "Could not retry outgoing connections.\n");
851 static int cmd_connect(int argc, char *argv[]) {
853 fprintf(stderr, "Invalid number of arguments.\n");
857 if(!check_id(argv[2])) {
858 fprintf(stderr, "Invalid name for node.\n");
865 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
866 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
867 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
874 static int cmd_disconnect(int argc, char *argv[]) {
876 fprintf(stderr, "Invalid number of arguments.\n");
880 if(!check_id(argv[2])) {
881 fprintf(stderr, "Invalid name for node.\n");
888 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
889 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
890 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
897 static int cmd_top(int argc, char *argv[]) {
905 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
910 static int cmd_pcap(int argc, char *argv[]) {
914 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
918 static int cmd_log(int argc, char *argv[]) {
922 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
926 static int cmd_pid(int argc, char *argv[]) {
934 static int rstrip(char *value) {
935 int len = strlen(value);
936 while(len && strchr("\t\r\n ", value[len - 1]))
941 static char *get_my_name() {
942 FILE *f = fopen(tinc_conf, "r");
944 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
950 while(fgets(buf, sizeof buf, f)) {
951 int len = strcspn(buf, "\t =");
953 value += strspn(value, "\t ");
956 value += strspn(value, "\t ");
961 if(strcasecmp(buf, "Name"))
965 return strdup(value);
970 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
974 static char *hostvariables[] = {
982 static int cmd_config(int argc, char *argv[]) {
984 fprintf(stderr, "Invalid number of arguments.\n");
989 if(!strcasecmp(argv[1], "add")) {
990 argv++, argc--, action = 1;
991 } else if(!strcasecmp(argv[1], "del")) {
992 argv++, argc--, action = -1;
993 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
994 argv++, argc--, action = 0;
998 fprintf(stderr, "Invalid number of arguments.\n");
1002 // Concatenate the rest of the command line
1003 strncpy(line, argv[1], sizeof line - 1);
1004 for(int i = 2; i < argc; i++) {
1005 strncat(line, " ", sizeof line - 1 - strlen(line));
1006 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1009 // Liberal parsing into node name, variable name and value.
1015 len = strcspn(line, "\t =");
1017 value += strspn(value, "\t ");
1020 value += strspn(value, "\t ");
1023 variable = strchr(line, '.');
1032 fprintf(stderr, "No variable given.\n");
1036 if(action >= 0 && !*value) {
1037 fprintf(stderr, "No value for variable given.\n");
1041 // Should this go into our own host config file?
1043 for(int i = 0; hostvariables[i]; i++) {
1044 if(!strcasecmp(hostvariables[i], variable)) {
1045 node = get_my_name();
1053 if(node && !check_id(node)) {
1054 fprintf(stderr, "Invalid name for node.\n");
1058 // Open the right configuration file.
1061 xasprintf(&filename, "%s/%s", hosts_dir, node);
1063 filename = tinc_conf;
1065 FILE *f = fopen(filename, "r");
1067 if(action < 0 || errno != ENOENT) {
1068 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1072 // If it doesn't exist, create it.
1073 f = fopen(filename, "a+");
1075 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1078 fprintf(stderr, "Created configuration file %s.\n", filename);
1083 xasprintf(&tmpfile, "%s.config.tmp", filename);
1084 FILE *tf = fopen(tmpfile, "w");
1086 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1090 // Copy the file, making modifications on the fly.
1094 bool removed = false;
1096 while(fgets(buf1, sizeof buf1, f)) {
1097 buf1[sizeof buf1 - 1] = 0;
1100 // Parse line in a simple way
1104 len = strcspn(buf2, "\t =");
1105 bvalue = buf2 + len;
1106 bvalue += strspn(bvalue, "\t ");
1107 if(*bvalue == '=') {
1109 bvalue += strspn(bvalue, "\t ");
1115 if(!strcasecmp(buf2, variable)) {
1118 if(!*value || !strcasecmp(bvalue, value)) {
1123 } else if(action == 0) {
1124 // Already set? Delete the rest...
1127 // Otherwise, replace.
1128 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1129 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1137 // Copy original line...
1138 if(fputs(buf1, tf) < 0) {
1139 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1144 // Make sure we read everything...
1145 if(ferror(f) || !feof(f)) {
1146 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1151 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1155 // Add new variable if necessary.
1156 if(action > 0 || (action == 0 && !set)) {
1157 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1158 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1163 // Make sure we wrote everything...
1165 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1169 // Could we find what we had to remove?
1170 if(action < 0 && !removed) {
1172 fprintf(stderr, "No configuration variables deleted.\n");
1176 // Replace the configuration file with the new one
1178 if(remove(filename)) {
1179 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1183 if(rename(tmpfile, filename)) {
1184 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1188 // Silently try notifying a running tincd of changes.
1192 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1197 bool check_id(const char *name) {
1198 for(int i = 0; i < strlen(name); i++) {
1199 if(!isalnum(name[i]) && name[i] != '_')
1206 static int cmd_init(int argc, char *argv[]) {
1207 if(!access(tinc_conf, F_OK)) {
1208 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1213 if(isatty(0) && isatty(1)) {
1215 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1217 if(!fgets(buf, sizeof buf, stdin)) {
1218 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1221 int len = rstrip(buf);
1223 fprintf(stderr, "No name given!\n");
1228 fprintf(stderr, "No Name given!\n");
1232 name = strdup(argv[1]);
1234 fprintf(stderr, "No Name given!\n");
1239 if(!check_id(name)) {
1240 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1244 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1245 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1249 if(mkdir(confbase, 0755) && errno != EEXIST) {
1250 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1254 char *hosts_dir = NULL;
1255 xasprintf(&hosts_dir, "%s/hosts", confbase);
1256 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1257 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1261 FILE *f = fopen(tinc_conf, "w");
1263 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1267 fprintf(f, "Name = %s\n", name);
1271 if(!rsa_keygen(2048) || !ecdsa_keygen())
1278 static int cmd_generate_keys(int argc, char *argv[]) {
1279 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1282 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1283 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1286 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1287 return !ecdsa_keygen();
1290 static int cmd_help(int argc, char *argv[]) {
1295 static int cmd_version(int argc, char *argv[]) {
1300 static int cmd_info(int argc, char *argv[]) {
1302 fprintf(stderr, "Invalid number of arguments.\n");
1306 if(!connect_tincd())
1309 return info(fd, argv[1]);
1312 static const char *conffiles[] = {
1323 static int cmd_edit(int argc, char *argv[]) {
1325 fprintf(stderr, "Invalid number of arguments.\n");
1329 char *filename = NULL;
1331 if(strncmp(argv[1], "hosts/", 6)) {
1332 for(int i = 0; conffiles[i]; i++) {
1333 if(!strcmp(argv[1], conffiles[i])) {
1334 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1343 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1344 char *dash = strchr(argv[1], '-');
1347 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1348 fprintf(stderr, "Invalid configuration filename.\n");
1355 char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1357 char *editor = "edit"
1361 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1362 int result = system(command);
1366 // Silently try notifying a running tincd of changes.
1370 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1375 static int export(const char *name, FILE *out) {
1377 xasprintf(&filename, "%s/%s", hosts_dir, name);
1378 FILE *in = fopen(filename, "r");
1380 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1384 fprintf(out, "Name = %s\n", name);
1386 while(fgets(buf, sizeof buf, in)) {
1387 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1392 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1400 static int cmd_export(int argc, char *argv[]) {
1401 char *name = get_my_name();
1405 return export(name, stdout);
1408 static int cmd_export_all(int argc, char *argv[]) {
1409 DIR *dir = opendir(hosts_dir);
1411 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1419 while((ent = readdir(dir))) {
1420 if(!check_id(ent->d_name))
1426 printf("#---------------------------------------------------------------#\n");
1428 result |= export(ent->d_name, stdout);
1435 static int cmd_import(int argc, char *argv[]) {
1443 bool firstline = true;
1445 while(fgets(buf, sizeof buf, in)) {
1446 if(sscanf(buf, "Name = %s", name) == 1) {
1447 if(!check_id(name)) {
1448 fprintf(stderr, "Invalid Name in input!\n");
1456 xasprintf(&filename, "%s/%s", hosts_dir, name);
1458 if(!force && !access(filename, F_OK)) {
1459 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1464 out = fopen(filename, "w");
1466 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1473 } else if(firstline) {
1474 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1479 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1483 if(fputs(buf, out) < 0) {
1484 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1494 fprintf(stderr, "Imported %d host configuration files.\n", count);
1497 fprintf(stderr, "No host configuration files imported.\n");
1502 static const struct {
1503 const char *command;
1504 int (*function)(int argc, char *argv[]);
1506 {"start", cmd_start},
1508 {"restart", cmd_restart},
1509 {"reload", cmd_reload},
1511 {"purge", cmd_purge},
1512 {"debug", cmd_debug},
1513 {"retry", cmd_retry},
1514 {"connect", cmd_connect},
1515 {"disconnect", cmd_disconnect},
1520 {"config", cmd_config},
1522 {"generate-keys", cmd_generate_keys},
1523 {"generate-rsa-keys", cmd_generate_rsa_keys},
1524 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1526 {"version", cmd_version},
1529 {"export", cmd_export},
1530 {"export-all", cmd_export_all},
1531 {"import", cmd_import},
1535 int main(int argc, char *argv[]) {
1536 program_name = argv[0];
1538 if(!parse_options(argc, argv))
1553 if(optind >= argc) {
1554 fprintf(stderr, "No command given.\n");
1559 for(int i = 0; commands[i].command; i++) {
1560 if(!strcasecmp(argv[optind], commands[i].command))
1561 return commands[i].function(argc - optind, argv + optind);
1564 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);