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");
838 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
839 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
840 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
847 static int cmd_disconnect(int argc, char *argv[]) {
849 fprintf(stderr, "Invalid number of arguments.\n");
856 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
857 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
858 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
865 static int cmd_top(int argc, char *argv[]) {
873 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
878 static int cmd_pcap(int argc, char *argv[]) {
882 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
886 static int cmd_log(int argc, char *argv[]) {
890 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
894 static int cmd_pid(int argc, char *argv[]) {
902 static int rstrip(char *value) {
903 int len = strlen(value);
904 while(len && strchr("\t\r\n ", value[len - 1]))
909 static char *get_my_name() {
910 FILE *f = fopen(tinc_conf, "r");
912 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
918 while(fgets(buf, sizeof buf, f)) {
919 int len = strcspn(buf, "\t =");
921 value += strspn(value, "\t ");
924 value += strspn(value, "\t ");
929 if(strcasecmp(buf, "Name"))
933 return strdup(value);
938 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
942 static char *hostvariables[] = {
950 static int cmd_config(int argc, char *argv[]) {
952 fprintf(stderr, "Invalid number of arguments.\n");
957 if(!strcasecmp(argv[1], "add")) {
958 argv++, argc--, action = 1;
959 } else if(!strcasecmp(argv[1], "del")) {
960 argv++, argc--, action = -1;
961 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
962 argv++, argc--, action = 0;
966 fprintf(stderr, "Invalid number of arguments.\n");
970 // Concatenate the rest of the command line
971 strncpy(line, argv[1], sizeof line - 1);
972 for(int i = 2; i < argc; i++) {
973 strncat(line, " ", sizeof line - 1 - strlen(line));
974 strncat(line, argv[i], sizeof line - 1 - strlen(line));
977 // Liberal parsing into node name, variable name and value.
983 len = strcspn(line, "\t =");
985 value += strspn(value, "\t ");
988 value += strspn(value, "\t ");
991 variable = strchr(line, '.');
1000 fprintf(stderr, "No variable given.\n");
1004 if(action >= 0 && !*value) {
1005 fprintf(stderr, "No value for variable given.\n");
1009 // Should this go into our own host config file?
1011 for(int i = 0; hostvariables[i]; i++) {
1012 if(!strcasecmp(hostvariables[i], variable)) {
1013 node = get_my_name();
1021 // Open the right configuration file.
1024 xasprintf(&filename, "%s/%s", hosts_dir, node);
1026 filename = tinc_conf;
1028 FILE *f = fopen(filename, "r");
1030 if(action < 0 || errno != ENOENT) {
1031 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1035 // If it doesn't exist, create it.
1036 f = fopen(filename, "a+");
1038 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1041 fprintf(stderr, "Created configuration file %s.\n", filename);
1046 xasprintf(&tmpfile, "%s.config.tmp", filename);
1047 FILE *tf = fopen(tmpfile, "w");
1049 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1053 // Copy the file, making modifications on the fly.
1057 bool removed = false;
1059 while(fgets(buf1, sizeof buf1, f)) {
1060 buf1[sizeof buf1 - 1] = 0;
1063 // Parse line in a simple way
1067 len = strcspn(buf2, "\t =");
1068 bvalue = buf2 + len;
1069 bvalue += strspn(bvalue, "\t ");
1070 if(*bvalue == '=') {
1072 bvalue += strspn(bvalue, "\t ");
1078 if(!strcasecmp(buf2, variable)) {
1081 if(!*value || !strcasecmp(bvalue, value)) {
1086 } else if(action == 0) {
1087 // Already set? Delete the rest...
1090 // Otherwise, replace.
1091 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1092 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1100 // Copy original line...
1101 if(fputs(buf1, tf) < 0) {
1102 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1107 // Make sure we read everything...
1108 if(ferror(f) || !feof(f)) {
1109 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1114 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1118 // Add new variable if necessary.
1119 if(action > 0 || (action == 0 && !set)) {
1120 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1121 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1126 // Make sure we wrote everything...
1128 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1132 // Could we find what we had to remove?
1133 if(action < 0 && !removed) {
1135 fprintf(stderr, "No configuration variables deleted.\n");
1139 // Replace the configuration file with the new one
1141 if(remove(filename)) {
1142 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1146 if(rename(tmpfile, filename)) {
1147 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1154 static int cmd_init(int argc, char *argv[]) {
1155 if(!access(tinc_conf, F_OK)) {
1156 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1161 if(isatty(0) && isatty(1)) {
1163 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1165 if(!fgets(buf, sizeof buf, stdin)) {
1166 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1169 int len = rstrip(buf);
1171 fprintf(stderr, "No name given!\n");
1176 fprintf(stderr, "No Name given!\n");
1180 name = strdup(argv[1]);
1182 fprintf(stderr, "No Name given!\n");
1187 for(int i = 0; i < strlen(name); i++) {
1188 if(!isalnum(name[i]) && name[i] != '_') {
1189 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1194 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1195 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1199 if(mkdir(confbase, 0755) && errno != EEXIST) {
1200 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1204 char *hosts_dir = NULL;
1205 xasprintf(&hosts_dir, "%s/hosts", confbase);
1206 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1207 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1211 FILE *f = fopen(tinc_conf, "w");
1213 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1217 fprintf(f, "Name = %s\n", name);
1221 if(!rsa_keygen(2048) || !ecdsa_keygen())
1228 static int cmd_generate_keys(int argc, char *argv[]) {
1229 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1232 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1233 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1236 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1237 return !ecdsa_keygen();
1240 static int cmd_help(int argc, char *argv[]) {
1245 static int cmd_version(int argc, char *argv[]) {
1250 static const struct {
1251 const char *command;
1252 int (*function)(int argc, char *argv[]);
1254 {"start", cmd_start},
1256 {"restart", cmd_restart},
1257 {"reload", cmd_reload},
1259 {"purge", cmd_purge},
1260 {"debug", cmd_debug},
1261 {"retry", cmd_retry},
1262 {"connect", cmd_connect},
1263 {"disconnect", cmd_disconnect},
1268 {"config", cmd_config},
1270 {"generate-keys", cmd_generate_keys},
1271 {"generate-rsa-keys", cmd_generate_rsa_keys},
1272 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1274 {"version", cmd_version},
1278 int main(int argc, char *argv[]) {
1279 program_name = argv[0];
1281 if(!parse_options(argc, argv))
1296 if(optind >= argc) {
1297 fprintf(stderr, "No command given.\n");
1302 for(int i = 0; commands[i].command; i++) {
1303 if(!strcasecmp(argv[optind], commands[i].command))
1304 return commands[i].function(argc - optind, argv + optind);
1307 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);