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.
25 #include "readline/readline.h"
26 #include "readline/history.h"
31 #include "control_common.h"
40 #define mkdir(a, b) mkdir(a)
44 /* The name this program was run with. */
45 static char *program_name = NULL;
47 static char **orig_argv;
50 /* If nonzero, display usage information and exit. */
51 static bool show_help = false;
53 /* If nonzero, print the version on standard output and exit. */
54 static bool show_version = false;
56 static char *name = NULL;
57 static char *identname = NULL; /* program name for syslog */
58 static char *pidfilename = NULL; /* pid file location */
59 static char *confdir = NULL;
60 static char controlcookie[1025];
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
67 // Horrible global variables...
70 static char line[4096];
74 static bool force = false;
75 static bool tty = true;
78 static struct WSAData wsa_state;
81 static struct option const long_options[] = {
82 {"config", required_argument, NULL, 'c'},
83 {"debug", optional_argument, NULL, 0},
84 {"no-detach", no_argument, NULL, 0},
85 {"mlock", no_argument, NULL, 0},
86 {"net", required_argument, NULL, 'n'},
87 {"help", no_argument, NULL, 1},
88 {"version", no_argument, NULL, 2},
89 {"pidfile", required_argument, NULL, 5},
90 {"logfile", required_argument, NULL, 0},
91 {"bypass-security", no_argument, NULL, 0},
92 {"chroot", no_argument, NULL, 0},
93 {"user", required_argument, NULL, 0},
94 {"option", required_argument, NULL, 0},
95 {"force", no_argument, NULL, 6},
99 static void version(void) {
100 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
101 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
102 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
103 "See the AUTHORS file for a complete list.\n\n"
104 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
105 "and you are welcome to redistribute it under certain conditions;\n"
106 "see the file COPYING for details.\n");
109 static void usage(bool status) {
111 fprintf(stderr, "Try `%s --help\' for more information.\n",
114 printf("Usage: %s [options] command\n\n", program_name);
115 printf("Valid options are:\n"
116 " -c, --config=DIR Read configuration options from DIR.\n"
117 " -n, --net=NETNAME Connect to net NETNAME.\n"
118 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
119 " --help Display this help and exit.\n"
120 " --version Output version information and exit.\n"
122 "Valid commands are:\n"
123 " init [name] Create initial configuration files.\n"
124 " config Change configuration:\n"
125 " [get] VARIABLE - print current value of VARIABLE\n"
126 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
127 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
128 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
129 " start [tincd options] Start tincd.\n"
130 " stop Stop tincd.\n"
131 " restart Restart tincd.\n"
132 " reload Partially reload configuration of running tincd.\n"
133 " pid Show PID of currently running tincd.\n"
134 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
135 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
136 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
137 " dump Dump a list of one of the following things:\n"
138 " nodes - all known nodes in the VPN\n"
139 " edges - all known connections in the VPN\n"
140 " subnets - all known subnets in the VPN\n"
141 " connections - all meta connections with ourself\n"
142 " [di]graph - graph of the VPN in dotty format\n"
143 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
144 " purge Purge unreachable nodes\n"
145 " debug N Set debug level\n"
146 " retry Retry all outgoing connections\n"
147 " disconnect NODE Close meta connection with NODE\n"
149 " top Show real-time statistics\n"
151 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
152 " log [level] Dump log output [up to the specified level]\n"
153 " export Export host configuration of local node to standard output\n"
154 " export-all Export all host configuration files to standard output\n"
155 " import [--force] Import host configuration file(s) from standard input\n"
157 printf("Report bugs to tinc@tinc-vpn.org.\n");
161 static bool parse_options(int argc, char **argv) {
163 int option_index = 0;
165 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
167 case 0: /* long option */
170 case 'c': /* config file */
171 confbase = xstrdup(optarg);
174 case 'n': /* net name given */
175 netname = xstrdup(optarg);
178 case 1: /* show help */
182 case 2: /* show version */
186 case 5: /* open control socket here */
187 pidfilename = xstrdup(optarg);
194 case '?': /* wrong options */
203 if(!netname && (netname = getenv("NETNAME")))
204 netname = xstrdup(netname);
206 /* netname "." is special: a "top-level name" */
208 if(netname && (!*netname || !strcmp(netname, "."))) {
213 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
214 fprintf(stderr, "Invalid character in netname!\n");
221 static void disable_old_keys(const char *filename, const char *what) {
222 char tmpfile[PATH_MAX] = "";
224 bool disabled = false;
229 r = fopen(filename, "r");
233 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
235 w = fopen(tmpfile, "w");
237 while(fgets(buf, sizeof buf, r)) {
238 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
239 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
245 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
251 if(block || ecdsapubkey)
253 if(fputs(buf, w) < 0) {
259 if(block && !strncmp(buf, "-----END ", 9))
266 if(ferror(r) || fclose(r) < 0)
271 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
278 // We cannot atomically replace files on Windows.
279 char bakfile[PATH_MAX] = "";
280 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
281 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
282 rename(bakfile, filename);
284 if(rename(tmpfile, filename)) {
286 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
291 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
298 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
304 /* Check stdin and stdout */
306 /* Ask for a file and/or directory name. */
307 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
311 if(fgets(buf, sizeof buf, stdin) == NULL) {
312 fprintf(stderr, "Error while reading stdin: %s\n",
317 size_t len = strlen(buf);
326 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
328 if(filename[0] != '/') {
330 /* The directory is a relative path or a filename. */
331 directory = get_current_dir_name();
332 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
336 umask(0077); /* Disallow everything for group and other */
338 disable_old_keys(filename, what);
340 /* Open it first to keep the inode busy */
342 r = fopen(filename, mode);
345 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
353 Generate a public/private ECDSA keypair, and ask for a file to store
356 static bool ecdsa_keygen(bool ask) {
359 char *pubname, *privname;
361 fprintf(stderr, "Generating ECDSA keypair:\n");
363 if(!ecdsa_generate(&key)) {
364 fprintf(stderr, "Error during key generation!\n");
367 fprintf(stderr, "Done.\n");
369 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
370 f = ask_and_open(privname, "private ECDSA key", "a", ask);
377 /* Make it unreadable for others. */
378 fchmod(fileno(f), 0600);
381 ecdsa_write_pem_private_key(&key, f);
386 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
388 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
390 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
396 char *pubkey = ecdsa_get_base64_public_key(&key);
397 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
406 Generate a public/private RSA keypair, and ask for a file to store
409 static bool rsa_keygen(int bits, bool ask) {
412 char *pubname, *privname;
414 fprintf(stderr, "Generating %d bits keys:\n", bits);
416 if(!rsa_generate(&key, bits, 0x10001)) {
417 fprintf(stderr, "Error during key generation!\n");
420 fprintf(stderr, "Done.\n");
422 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
423 f = ask_and_open(privname, "private RSA key", "a", ask);
430 /* Make it unreadable for others. */
431 fchmod(fileno(f), 0600);
434 rsa_write_pem_private_key(&key, f);
439 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
441 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
443 f = ask_and_open(pubname, "public RSA key", "a", ask);
449 rsa_write_pem_public_key(&key, f);
457 Set all files and paths according to netname
459 static void make_names(void) {
462 char installdir[1024] = "";
463 long len = sizeof installdir;
467 xasprintf(&identname, "tinc.%s", netname);
469 identname = xstrdup("tinc");
472 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
473 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
476 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
478 xasprintf(&confbase, "%s", installdir);
482 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
488 confdir = xstrdup(CONFDIR);
491 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
495 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
497 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
500 xasprintf(&confbase, CONFDIR SLASH "tinc");
505 confdir = xstrdup(installdir);
508 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
509 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
512 static char buffer[4096];
513 static size_t blen = 0;
515 bool recvline(int fd, char *line, size_t len) {
516 char *newline = NULL;
518 while(!(newline = memchr(buffer, '\n', blen))) {
519 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
520 if(result == -1 && errno == EINTR)
527 if(newline - buffer >= len)
530 len = newline - buffer;
532 memcpy(line, buffer, len);
534 memmove(buffer, newline + 1, blen - len - 1);
540 static bool recvdata(int fd, char *data, size_t len) {
542 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
543 if(result == -1 && errno == EINTR)
550 memcpy(data, buffer, len);
551 memmove(buffer, buffer + len, blen - len);
557 bool sendline(int fd, char *format, ...) {
558 static char buffer[4096];
563 va_start(ap, format);
564 blen = vsnprintf(buffer, sizeof buffer, format, ap);
567 if(blen < 1 || blen >= sizeof buffer)
574 int result = send(fd, p, blen, 0);
575 if(result == -1 && errno == EINTR)
586 static void pcap(int fd, FILE *out, int snaplen) {
587 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
595 uint32_t tz_accuracy;
602 snaplen ?: sizeof data,
615 fwrite(&header, sizeof header, 1, out);
619 while(recvline(fd, line, sizeof line)) {
621 int n = sscanf(line, "%d %d %d", &code, &req, &len);
622 gettimeofday(&tv, NULL);
623 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
625 if(!recvdata(fd, data, len))
627 packet.tv_sec = tv.tv_sec;
628 packet.tv_usec = tv.tv_usec;
630 packet.origlen = len;
631 fwrite(&packet, sizeof packet, 1, out);
632 fwrite(data, len, 1, out);
637 static void logcontrol(int fd, FILE *out, int level) {
638 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
642 while(recvline(fd, line, sizeof line)) {
644 int n = sscanf(line, "%d %d %d", &code, &req, &len);
645 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
647 if(!recvdata(fd, data, len))
649 fwrite(data, len, 1, out);
656 static bool remove_service(void) {
657 SC_HANDLE manager = NULL;
658 SC_HANDLE service = NULL;
659 SERVICE_STATUS status = {0};
661 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
663 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
667 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
670 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
674 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
675 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
677 fprintf(stderr, "%s service stopped\n", identname);
679 if(!DeleteService(service)) {
680 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
684 fprintf(stderr, "%s service removed\n", identname);
690 static bool connect_tincd(bool verbose) {
695 struct timeval tv = {0, 0};
696 if(select(fd + 1, &r, NULL, NULL, &tv)) {
697 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
705 FILE *f = fopen(pidfilename, "r");
708 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
715 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
717 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
725 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
727 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
732 struct addrinfo hints = {
733 .ai_family = AF_UNSPEC,
734 .ai_socktype = SOCK_STREAM,
735 .ai_protocol = IPPROTO_TCP,
739 struct addrinfo *res = NULL;
741 if(getaddrinfo(host, port, &hints, &res) || !res) {
743 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
747 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
750 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
755 unsigned long arg = 0;
757 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
759 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
763 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
765 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
776 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
778 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
784 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
786 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
788 fprintf(stderr, "Could not fully establish control socket connection\n");
798 static int cmd_start(int argc, char *argv[]) {
799 if(connect_tincd(false)) {
801 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
803 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
808 char *slash = strrchr(program_name, '/');
811 if ((c = strrchr(program_name, '\\')) > slash)
816 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
821 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
824 for(int i = 1; i < optind; i++)
825 nargv[nargc++] = orig_argv[i];
826 for(int i = 1; i < argc; i++)
827 nargv[nargc++] = argv[i];
831 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
836 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
842 exit(execvp(c, nargv));
847 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
848 fprintf(stderr, "Error starting %s\n", c);
856 static int cmd_stop(int argc, char *argv[]) {
858 if(!connect_tincd(true)) {
860 if(kill(pid, SIGTERM)) {
861 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
865 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
866 waitpid(pid, NULL, 0);
873 sendline(fd, "%d %d", CONTROL, REQ_STOP);
874 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
875 fprintf(stderr, "Could not stop tinc daemon.\n");
879 // Wait for tincd to close the connection...
883 select(fd + 1, &r, NULL, NULL, NULL);
885 if(!remove_service())
895 static int cmd_restart(int argc, char *argv[]) {
896 cmd_stop(argc, argv);
897 return cmd_start(argc, argv);
900 static int cmd_reload(int argc, char *argv[]) {
901 if(!connect_tincd(true))
904 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
905 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
906 fprintf(stderr, "Could not reload configuration.\n");
914 static int cmd_dump(int argc, char *argv[]) {
916 fprintf(stderr, "Invalid number of arguments.\n");
921 if(!connect_tincd(true))
926 if(!strcasecmp(argv[1], "nodes"))
927 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
928 else if(!strcasecmp(argv[1], "edges"))
929 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
930 else if(!strcasecmp(argv[1], "subnets"))
931 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
932 else if(!strcasecmp(argv[1], "connections"))
933 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
934 else if(!strcasecmp(argv[1], "graph")) {
935 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
936 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
938 } else if(!strcasecmp(argv[1], "digraph")) {
939 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
940 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
943 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
950 else if(do_graph == 2)
951 printf("digraph {\n");
953 while(recvline(fd, line, sizeof line)) {
954 char node1[4096], node2[4096];
955 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
957 if(do_graph && req == REQ_DUMP_NODES)
976 int cipher, digest, maclength, compression, distance, socket, weight;
977 short int pmtu, minmtu, maxmtu;
978 unsigned int options, status_int;
979 node_status_t status;
980 long int last_state_change;
983 case REQ_DUMP_NODES: {
984 int n = sscanf(line, "%*d %*d %s %s port %s %d %d %d %d %x %x %s %s %d %hd %hd %hd %ld", node, host, port, &cipher, &digest, &maclength, &compression, &options, &status_int, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change);
986 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
990 memcpy(&status, &status_int, sizeof status);
991 const char *color = "black";
992 if(!strcmp(host, "MYSELF"))
994 else if(!status.reachable)
996 else if(strcmp(via, node))
998 else if(!status.validkey)
1002 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1004 printf("%s at %s port %s cipher %d digest %d maclength %d compression %d options %x status %04x nexthop %s via %s distance %d pmtu %hd (min %hd max %hd)\n",
1005 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1009 case REQ_DUMP_EDGES: {
1010 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1012 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1017 float w = 1 + 65536.0 / weight;
1018 if(do_graph == 1 && strcmp(node1, node2) > 0)
1019 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1020 else if(do_graph == 2)
1021 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1023 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1027 case REQ_DUMP_SUBNETS: {
1028 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1030 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1033 printf("%s owner %s\n", strip_weight(subnet), node);
1036 case REQ_DUMP_CONNECTIONS: {
1037 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1039 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1042 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1046 fprintf(stderr, "Unable to parse dump from tincd.\n");
1051 fprintf(stderr, "Error receiving dump.\n");
1055 static int cmd_purge(int argc, char *argv[]) {
1056 if(!connect_tincd(true))
1059 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1060 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1061 fprintf(stderr, "Could not purge old information.\n");
1068 static int cmd_debug(int argc, char *argv[]) {
1070 fprintf(stderr, "Invalid number of arguments.\n");
1074 if(!connect_tincd(true))
1077 int debuglevel = atoi(argv[1]);
1080 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1081 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1082 fprintf(stderr, "Could not set debug level.\n");
1086 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1090 static int cmd_retry(int argc, char *argv[]) {
1091 if(!connect_tincd(true))
1094 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1095 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1096 fprintf(stderr, "Could not retry outgoing connections.\n");
1103 static int cmd_connect(int argc, char *argv[]) {
1105 fprintf(stderr, "Invalid number of arguments.\n");
1109 if(!check_id(argv[1])) {
1110 fprintf(stderr, "Invalid name for node.\n");
1114 if(!connect_tincd(true))
1117 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1118 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1119 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1126 static int cmd_disconnect(int argc, char *argv[]) {
1128 fprintf(stderr, "Invalid number of arguments.\n");
1132 if(!check_id(argv[1])) {
1133 fprintf(stderr, "Invalid name for node.\n");
1137 if(!connect_tincd(true))
1140 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1141 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1142 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1149 static int cmd_top(int argc, char *argv[]) {
1151 if(!connect_tincd(true))
1157 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1162 static int cmd_pcap(int argc, char *argv[]) {
1163 if(!connect_tincd(true))
1166 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1170 static int cmd_log(int argc, char *argv[]) {
1171 if(!connect_tincd(true))
1174 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1178 static int cmd_pid(int argc, char *argv[]) {
1179 if(!connect_tincd(true) && !pid)
1182 printf("%d\n", pid);
1186 static int rstrip(char *value) {
1187 int len = strlen(value);
1188 while(len && strchr("\t\r\n ", value[len - 1]))
1193 static char *get_my_name() {
1194 FILE *f = fopen(tinc_conf, "r");
1196 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1202 while(fgets(buf, sizeof buf, f)) {
1203 int len = strcspn(buf, "\t =");
1205 value += strspn(value, "\t ");
1208 value += strspn(value, "\t ");
1213 if(strcasecmp(buf, "Name"))
1217 return strdup(value);
1222 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1226 #define VAR_SERVER 1 /* Should be in tinc.conf */
1227 #define VAR_HOST 2 /* Can be in host config file */
1228 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1229 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1234 } const variables[] = {
1235 /* Server configuration */
1236 {"AddressFamily", VAR_SERVER},
1237 {"AutoConnect", VAR_SERVER},
1238 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1239 {"BindToInterface", VAR_SERVER},
1240 {"Broadcast", VAR_SERVER},
1241 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1242 {"DecrementTTL", VAR_SERVER},
1243 {"Device", VAR_SERVER},
1244 {"DeviceType", VAR_SERVER},
1245 {"DirectOnly", VAR_SERVER},
1246 {"ECDSAPrivateKeyFile", VAR_SERVER},
1247 {"ExperimentalProtocol", VAR_SERVER},
1248 {"Forwarding", VAR_SERVER},
1249 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1250 {"Hostnames", VAR_SERVER},
1251 {"IffOneQueue", VAR_SERVER},
1252 {"Interface", VAR_SERVER},
1253 {"KeyExpire", VAR_SERVER},
1254 {"LocalDiscovery", VAR_SERVER},
1255 {"MACExpire", VAR_SERVER},
1256 {"MaxOutputBufferSize", VAR_SERVER},
1257 {"MaxTimeout", VAR_SERVER},
1258 {"Mode", VAR_SERVER},
1259 {"Name", VAR_SERVER},
1260 {"PingInterval", VAR_SERVER},
1261 {"PingTimeout", VAR_SERVER},
1262 {"PriorityInheritance", VAR_SERVER},
1263 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1264 {"PrivateKeyFile", VAR_SERVER},
1265 {"ProcessPriority", VAR_SERVER},
1266 {"Proxy", VAR_SERVER},
1267 {"ReplayWindow", VAR_SERVER},
1268 {"ScriptsExtension", VAR_SERVER},
1269 {"ScriptsInterpreter", VAR_SERVER},
1270 {"StrictSubnets", VAR_SERVER},
1271 {"TunnelServer", VAR_SERVER},
1272 {"UDPRcvBuf", VAR_SERVER},
1273 {"UDPSndBuf", VAR_SERVER},
1274 {"VDEGroup", VAR_SERVER},
1275 {"VDEPort", VAR_SERVER},
1276 /* Host configuration */
1277 {"Address", VAR_HOST | VAR_MULTIPLE},
1278 {"Cipher", VAR_SERVER | VAR_HOST},
1279 {"ClampMSS", VAR_SERVER | VAR_HOST},
1280 {"Compression", VAR_SERVER | VAR_HOST},
1281 {"Digest", VAR_SERVER | VAR_HOST},
1282 {"ECDSAPublicKey", VAR_HOST},
1283 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1284 {"IndirectData", VAR_SERVER | VAR_HOST},
1285 {"MACLength", VAR_SERVER | VAR_HOST},
1286 {"PMTU", VAR_SERVER | VAR_HOST},
1287 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1289 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1290 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1291 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1292 {"TCPOnly", VAR_SERVER | VAR_HOST},
1293 {"Weight", VAR_HOST},
1297 static int cmd_config(int argc, char *argv[]) {
1299 fprintf(stderr, "Invalid number of arguments.\n");
1304 if(!strcasecmp(argv[1], "get")) {
1306 } else if(!strcasecmp(argv[1], "add")) {
1307 argv++, argc--, action = 1;
1308 } else if(!strcasecmp(argv[1], "del")) {
1309 argv++, argc--, action = -1;
1310 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1311 argv++, argc--, action = 0;
1315 fprintf(stderr, "Invalid number of arguments.\n");
1319 // Concatenate the rest of the command line
1320 strncpy(line, argv[1], sizeof line - 1);
1321 for(int i = 2; i < argc; i++) {
1322 strncat(line, " ", sizeof line - 1 - strlen(line));
1323 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1326 // Liberal parsing into node name, variable name and value.
1332 len = strcspn(line, "\t =");
1334 value += strspn(value, "\t ");
1337 value += strspn(value, "\t ");
1340 variable = strchr(line, '.');
1349 fprintf(stderr, "No variable given.\n");
1353 if(action >= 0 && !*value) {
1354 fprintf(stderr, "No value for variable given.\n");
1358 if(action < -1 && *value)
1361 /* Some simple checks. */
1364 for(int i = 0; variables[i].name; i++) {
1365 if(strcasecmp(variables[i].name, variable))
1369 variable = (char *)variables[i].name;
1371 /* Discourage use of obsolete variables. */
1373 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1375 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1377 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1382 /* Don't put server variables in host config files */
1384 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1386 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1388 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1393 /* Should this go into our own host config file? */
1395 if(!node && !(variables[i].type & VAR_SERVER)) {
1396 node = get_my_name();
1404 if(node && !check_id(node)) {
1405 fprintf(stderr, "Invalid name for node.\n");
1410 if(force || action < 0) {
1411 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1413 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1418 // Open the right configuration file.
1421 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1423 filename = tinc_conf;
1425 FILE *f = fopen(filename, "r");
1427 if(action < 0 || errno != ENOENT) {
1428 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1432 // If it doesn't exist, create it.
1433 f = fopen(filename, "a+");
1435 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1438 fprintf(stderr, "Created configuration file %s.\n", filename);
1442 char *tmpfile = NULL;
1446 xasprintf(&tmpfile, "%s.config.tmp", filename);
1447 tf = fopen(tmpfile, "w");
1449 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1455 // Copy the file, making modifications on the fly, unless we are just getting a value.
1459 bool removed = false;
1462 while(fgets(buf1, sizeof buf1, f)) {
1463 buf1[sizeof buf1 - 1] = 0;
1464 strncpy(buf2, buf1, sizeof buf2);
1466 // Parse line in a simple way
1470 len = strcspn(buf2, "\t =");
1471 bvalue = buf2 + len;
1472 bvalue += strspn(bvalue, "\t ");
1473 if(*bvalue == '=') {
1475 bvalue += strspn(bvalue, "\t ");
1481 if(!strcasecmp(buf2, variable)) {
1485 printf("%s\n", bvalue);
1487 } else if(action == -1) {
1488 if(!*value || !strcasecmp(bvalue, value)) {
1493 } else if(action == 0) {
1494 // Already set? Delete the rest...
1497 // Otherwise, replace.
1498 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1499 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1508 // Copy original line...
1509 if(fputs(buf1, tf) < 0) {
1510 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1514 // Add newline if it is missing...
1515 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1516 if(fputc('\n', tf) < 0) {
1517 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1524 // Make sure we read everything...
1525 if(ferror(f) || !feof(f)) {
1526 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1531 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1535 // Add new variable if necessary.
1536 if(action > 0 || (action == 0 && !set)) {
1537 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1538 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1545 fprintf(stderr, "No matching configuration variables found.\n");
1549 // Make sure we wrote everything...
1551 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1555 // Could we find what we had to remove?
1556 if(action < 0 && !removed) {
1558 fprintf(stderr, "No configuration variables deleted.\n");
1562 // Replace the configuration file with the new one
1564 if(remove(filename)) {
1565 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1569 if(rename(tmpfile, filename)) {
1570 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1574 // Silently try notifying a running tincd of changes.
1575 if(connect_tincd(false))
1576 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1581 bool check_id(const char *name) {
1585 for(int i = 0; i < strlen(name); i++) {
1586 if(!isalnum(name[i]) && name[i] != '_')
1593 static int cmd_init(int argc, char *argv[]) {
1594 if(!access(tinc_conf, F_OK)) {
1595 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1602 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1604 if(!fgets(buf, sizeof buf, stdin)) {
1605 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1608 int len = rstrip(buf);
1610 fprintf(stderr, "No name given!\n");
1615 fprintf(stderr, "No Name given!\n");
1619 name = strdup(argv[1]);
1621 fprintf(stderr, "No Name given!\n");
1626 if(!check_id(name)) {
1627 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1631 if(mkdir(confdir, 0755) && errno != EEXIST) {
1632 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1636 if(mkdir(confbase, 0755) && errno != EEXIST) {
1637 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1641 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1642 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1646 FILE *f = fopen(tinc_conf, "w");
1648 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1652 fprintf(f, "Name = %s\n", name);
1655 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1660 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1661 if(access(filename, F_OK)) {
1662 FILE *f = fopen(filename, "w");
1664 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1667 fchmod(fileno(f), 0755);
1668 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1677 static int cmd_generate_keys(int argc, char *argv[]) {
1678 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1681 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1682 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1685 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1686 return !ecdsa_keygen(true);
1689 static int cmd_help(int argc, char *argv[]) {
1694 static int cmd_version(int argc, char *argv[]) {
1699 static int cmd_info(int argc, char *argv[]) {
1701 fprintf(stderr, "Invalid number of arguments.\n");
1705 if(!connect_tincd(true))
1708 return info(fd, argv[1]);
1711 static const char *conffiles[] = {
1722 static int cmd_edit(int argc, char *argv[]) {
1724 fprintf(stderr, "Invalid number of arguments.\n");
1728 char *filename = NULL;
1730 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1731 for(int i = 0; conffiles[i]; i++) {
1732 if(!strcmp(argv[1], conffiles[i])) {
1733 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1742 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1743 char *dash = strchr(argv[1], '-');
1746 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1747 fprintf(stderr, "Invalid configuration filename.\n");
1755 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1757 xasprintf(&command, "edit \"%s\"", filename);
1759 int result = system(command);
1763 // Silently try notifying a running tincd of changes.
1764 if(connect_tincd(false))
1765 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1770 static int export(const char *name, FILE *out) {
1772 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1773 FILE *in = fopen(filename, "r");
1775 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1779 fprintf(out, "Name = %s\n", name);
1781 while(fgets(buf, sizeof buf, in)) {
1782 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1787 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1796 static int cmd_export(int argc, char *argv[]) {
1797 char *name = get_my_name();
1801 return export(name, stdout);
1804 static int cmd_export_all(int argc, char *argv[]) {
1805 DIR *dir = opendir(hosts_dir);
1807 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1815 while((ent = readdir(dir))) {
1816 if(!check_id(ent->d_name))
1822 printf("#---------------------------------------------------------------#\n");
1824 result |= export(ent->d_name, stdout);
1831 static int cmd_import(int argc, char *argv[]) {
1839 bool firstline = true;
1841 while(fgets(buf, sizeof buf, in)) {
1842 if(sscanf(buf, "Name = %s", name) == 1) {
1843 if(!check_id(name)) {
1844 fprintf(stderr, "Invalid Name in input!\n");
1852 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1854 if(!force && !access(filename, F_OK)) {
1855 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1860 out = fopen(filename, "w");
1862 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1869 } else if(firstline) {
1870 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1875 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1879 if(fputs(buf, out) < 0) {
1880 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1890 fprintf(stderr, "Imported %d host configuration files.\n", count);
1893 fprintf(stderr, "No host configuration files imported.\n");
1898 static const struct {
1899 const char *command;
1900 int (*function)(int argc, char *argv[]);
1902 {"start", cmd_start},
1904 {"restart", cmd_restart},
1905 {"reload", cmd_reload},
1907 {"purge", cmd_purge},
1908 {"debug", cmd_debug},
1909 {"retry", cmd_retry},
1910 {"connect", cmd_connect},
1911 {"disconnect", cmd_disconnect},
1916 {"config", cmd_config},
1918 {"generate-keys", cmd_generate_keys},
1919 {"generate-rsa-keys", cmd_generate_rsa_keys},
1920 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1922 {"version", cmd_version},
1925 {"export", cmd_export},
1926 {"export-all", cmd_export_all},
1927 {"import", cmd_import},
1931 #ifdef HAVE_READLINE
1932 static char *complete_command(const char *text, int state) {
1940 while(commands[i].command) {
1941 if(!strncasecmp(commands[i].command, text, strlen(text)))
1942 return xstrdup(commands[i].command);
1949 static char *complete_dump(const char *text, int state) {
1950 const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1959 if(!strncasecmp(matches[i], text, strlen(text)))
1960 return xstrdup(matches[i]);
1967 static char *complete_config(const char *text, int state) {
1968 const char *sub[] = {"get", "set", "add", "del"};
1972 if(!strchr(rl_line_buffer + 7, ' '))
1976 for(int i = 0; i < 4; i++) {
1977 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1989 while(i < 0 || variables[i].name) {
1990 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
1991 return xstrdup(sub[i + 4]);
1993 char *dot = strchr(text, '.');
1995 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
1997 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2001 if(!strncasecmp(variables[i].name, text, strlen(text)))
2002 return xstrdup(variables[i].name);
2011 static char *complete_info(const char *text, int state) {
2015 if(!connect_tincd(false))
2017 // Check the list of nodes
2018 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2019 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2022 while(recvline(fd, line, sizeof line)) {
2024 int n = sscanf(line, "%d %d %s", &code, &req, item);
2034 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2038 if(!strncmp(item, text, strlen(text)))
2039 return xstrdup(strip_weight(item));
2045 static char *complete_nothing(const char *text, int state) {
2049 static char **completion (const char *text, int start, int end) {
2050 char **matches = NULL;
2053 matches = rl_completion_matches(text, complete_command);
2054 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2055 matches = rl_completion_matches(text, complete_dump);
2056 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2057 matches = rl_completion_matches(text, complete_config);
2058 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2059 matches = rl_completion_matches(text, complete_info);
2065 static int cmd_shell(int argc, char *argv[]) {
2067 xasprintf(&prompt, "%s> ", identname);
2071 int maxargs = argc + 16;
2072 char **nargv = xmalloc(maxargs * sizeof *nargv);
2074 for(int i = 0; i < argc; i++)
2077 #ifdef HAVE_READLINE
2078 rl_readline_name = "tinc";
2079 rl_completion_entry_function = complete_nothing;
2080 rl_attempted_completion_function = completion;
2081 rl_filename_completion_desired = 0;
2086 #ifdef HAVE_READLINE
2090 rl_basic_word_break_characters = "\t\n ";
2091 line = readline(prompt);
2093 copy = xstrdup(line);
2095 line = fgets(buf, sizeof buf, stdin);
2099 fputs(prompt, stdout);
2101 line = fgets(buf, sizeof buf, stdin);
2107 /* Ignore comments */
2115 char *p = line + strspn(line, " \t\n");
2116 char *next = strtok(p, " \t\n");
2119 if(nargc >= maxargs) {
2120 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2123 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2128 next = strtok(NULL, " \t\n");
2134 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2139 for(int i = 0; commands[i].command; i++) {
2140 if(!strcasecmp(nargv[argc], commands[i].command)) {
2141 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2147 #ifdef HAVE_READLINE
2153 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2166 int main(int argc, char *argv[]) {
2167 program_name = argv[0];
2171 if(!parse_options(argc, argv))
2186 tty = isatty(0) && isatty(1);
2189 return cmd_shell(argc, argv);
2191 for(int i = 0; commands[i].command; i++) {
2192 if(!strcasecmp(argv[optind], commands[i].command))
2193 return commands[i].function(argc - optind, argv + optind);
2196 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);