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[1024];
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
66 // Horrible global variables...
69 static char line[4096];
73 static bool force = false;
74 static bool tty = true;
77 static struct WSAData wsa_state;
80 static struct option const long_options[] = {
81 {"config", required_argument, NULL, 'c'},
82 {"debug", optional_argument, NULL, 0},
83 {"no-detach", no_argument, NULL, 0},
84 {"mlock", no_argument, NULL, 0},
85 {"net", required_argument, NULL, 'n'},
86 {"help", no_argument, NULL, 1},
87 {"version", no_argument, NULL, 2},
88 {"pidfile", required_argument, NULL, 5},
89 {"logfile", required_argument, NULL, 0},
90 {"bypass-security", no_argument, NULL, 0},
91 {"chroot", no_argument, NULL, 0},
92 {"user", required_argument, NULL, 0},
93 {"option", required_argument, NULL, 0},
94 {"force", no_argument, NULL, 6},
98 static void version(void) {
99 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
100 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
101 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
102 "See the AUTHORS file for a complete list.\n\n"
103 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
104 "and you are welcome to redistribute it under certain conditions;\n"
105 "see the file COPYING for details.\n");
108 static void usage(bool status) {
110 fprintf(stderr, "Try `%s --help\' for more information.\n",
113 printf("Usage: %s [options] command\n\n", program_name);
114 printf("Valid options are:\n"
115 " -c, --config=DIR Read configuration options from DIR.\n"
116 " -n, --net=NETNAME Connect to net NETNAME.\n"
117 " --pidfile=FILENAME Read control cookie from FILENAME.\n"
118 " --help Display this help and exit.\n"
119 " --version Output version information and exit.\n"
121 "Valid commands are:\n"
122 " init [name] Create initial configuration files.\n"
123 " config Change configuration:\n"
124 " [get] VARIABLE - print current value of VARIABLE\n"
125 " [set] VARIABLE VALUE - set VARIABLE to VALUE\n"
126 " add VARIABLE VALUE - add VARIABLE with the given VALUE\n"
127 " del VARIABLE [VALUE] - remove VARIABLE [only ones with watching VALUE]\n"
128 " start [tincd options] Start tincd.\n"
129 " stop Stop tincd.\n"
130 " restart Restart tincd.\n"
131 " reload Partially reload configuration of running tincd.\n"
132 " pid Show PID of currently running tincd.\n"
133 " generate-keys [bits] Generate new RSA and ECDSA public/private keypairs.\n"
134 " generate-rsa-keys [bits] Generate a new RSA public/private keypair.\n"
135 " generate-ecdsa-keys Generate a new ECDSA public/private keypair.\n"
136 " dump Dump a list of one of the following things:\n"
137 " nodes - all known nodes in the VPN\n"
138 " edges - all known connections in the VPN\n"
139 " subnets - all known subnets in the VPN\n"
140 " connections - all meta connections with ourself\n"
141 " [di]graph - graph of the VPN in dotty format\n"
142 " info NODE|SUBNET|ADDRESS Give information about a particular NODE, SUBNET or ADDRESS.\n"
143 " purge Purge unreachable nodes\n"
144 " debug N Set debug level\n"
145 " retry Retry all outgoing connections\n"
146 " disconnect NODE Close meta connection with NODE\n"
148 " top Show real-time statistics\n"
150 " pcap [snaplen] Dump traffic in pcap format [up to snaplen bytes per packet]\n"
151 " log [level] Dump log output [up to the specified level]\n"
152 " export Export host configuration of local node to standard output\n"
153 " export-all Export all host configuration files to standard output\n"
154 " import [--force] Import host configuration file(s) from standard input\n"
156 printf("Report bugs to tinc@tinc-vpn.org.\n");
160 static bool parse_options(int argc, char **argv) {
162 int option_index = 0;
164 while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
166 case 0: /* long option */
169 case 'c': /* config file */
170 confbase = xstrdup(optarg);
173 case 'n': /* net name given */
174 netname = xstrdup(optarg);
177 case 1: /* show help */
181 case 2: /* show version */
185 case 5: /* open control socket here */
186 pidfilename = xstrdup(optarg);
193 case '?': /* wrong options */
202 if(!netname && (netname = getenv("NETNAME")))
203 netname = xstrdup(netname);
205 /* netname "." is special: a "top-level name" */
207 if(netname && (!*netname || !strcmp(netname, "."))) {
212 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
213 fprintf(stderr, "Invalid character in netname!\n");
220 static void disable_old_keys(const char *filename, const char *what) {
221 char tmpfile[PATH_MAX] = "";
223 bool disabled = false;
228 r = fopen(filename, "r");
232 snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
234 w = fopen(tmpfile, "w");
236 while(fgets(buf, sizeof buf, r)) {
237 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
238 if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
244 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
250 if(block || ecdsapubkey)
252 if(fputs(buf, w) < 0) {
258 if(block && !strncmp(buf, "-----END ", 9))
265 if(ferror(r) || fclose(r) < 0)
270 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
277 // We cannot atomically replace files on Windows.
278 char bakfile[PATH_MAX] = "";
279 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
280 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
281 rename(bakfile, filename);
283 if(rename(tmpfile, filename)) {
285 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
290 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
297 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
303 /* Check stdin and stdout */
305 /* Ask for a file and/or directory name. */
306 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
310 if(fgets(buf, sizeof buf, stdin) == NULL) {
311 fprintf(stderr, "Error while reading stdin: %s\n",
316 size_t len = strlen(buf);
325 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
327 if(filename[0] != '/') {
329 /* The directory is a relative path or a filename. */
330 directory = get_current_dir_name();
331 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
335 umask(0077); /* Disallow everything for group and other */
337 disable_old_keys(filename, what);
339 /* Open it first to keep the inode busy */
341 r = fopen(filename, mode);
344 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
352 Generate a public/private ECDSA keypair, and ask for a file to store
355 static bool ecdsa_keygen(bool ask) {
358 char *pubname, *privname;
360 fprintf(stderr, "Generating ECDSA keypair:\n");
362 if(!ecdsa_generate(&key)) {
363 fprintf(stderr, "Error during key generation!\n");
366 fprintf(stderr, "Done.\n");
368 xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
369 f = ask_and_open(privname, "private ECDSA key", "a", ask);
376 /* Make it unreadable for others. */
377 fchmod(fileno(f), 0600);
380 ecdsa_write_pem_private_key(&key, f);
385 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
387 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
389 f = ask_and_open(pubname, "public ECDSA key", "a", ask);
395 char *pubkey = ecdsa_get_base64_public_key(&key);
396 fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
405 Generate a public/private RSA keypair, and ask for a file to store
408 static bool rsa_keygen(int bits, bool ask) {
411 char *pubname, *privname;
413 fprintf(stderr, "Generating %d bits keys:\n", bits);
415 if(!rsa_generate(&key, bits, 0x10001)) {
416 fprintf(stderr, "Error during key generation!\n");
419 fprintf(stderr, "Done.\n");
421 xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
422 f = ask_and_open(privname, "private RSA key", "a", ask);
429 /* Make it unreadable for others. */
430 fchmod(fileno(f), 0600);
433 rsa_write_pem_private_key(&key, f);
438 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
440 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
442 f = ask_and_open(pubname, "public RSA key", "a", ask);
448 rsa_write_pem_public_key(&key, f);
456 Set all files and paths according to netname
458 static void make_names(void) {
461 char installdir[1024] = "";
462 long len = sizeof installdir;
466 xasprintf(&identname, "tinc.%s", netname);
468 identname = xstrdup("tinc");
471 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
472 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
475 xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
477 xasprintf(&confbase, "%s", installdir);
481 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
487 confdir = xstrdup(CONFDIR);
490 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
494 xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
496 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
499 xasprintf(&confbase, CONFDIR SLASH "tinc");
504 confdir = xstrdup(installdir);
507 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
508 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
511 static char buffer[4096];
512 static size_t blen = 0;
514 bool recvline(int fd, char *line, size_t len) {
515 char *newline = NULL;
517 while(!(newline = memchr(buffer, '\n', blen))) {
518 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
519 if(result == -1 && errno == EINTR)
526 if(newline - buffer >= len)
529 len = newline - buffer;
531 memcpy(line, buffer, len);
533 memmove(buffer, newline + 1, blen - len - 1);
539 static bool recvdata(int fd, char *data, size_t len) {
541 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
542 if(result == -1 && errno == EINTR)
549 memcpy(data, buffer, len);
550 memmove(buffer, buffer + len, blen - len);
556 bool sendline(int fd, char *format, ...) {
557 static char buffer[4096];
562 va_start(ap, format);
563 blen = vsnprintf(buffer, sizeof buffer, format, ap);
566 if(blen < 1 || blen >= sizeof buffer)
573 int result = send(fd, p, blen, 0);
574 if(result == -1 && errno == EINTR)
585 static void pcap(int fd, FILE *out, int snaplen) {
586 sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
594 uint32_t tz_accuracy;
601 snaplen ?: sizeof data,
614 fwrite(&header, sizeof header, 1, out);
618 while(recvline(fd, line, sizeof line)) {
620 int n = sscanf(line, "%d %d %d", &code, &req, &len);
621 gettimeofday(&tv, NULL);
622 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
624 if(!recvdata(fd, data, len))
626 packet.tv_sec = tv.tv_sec;
627 packet.tv_usec = tv.tv_usec;
629 packet.origlen = len;
630 fwrite(&packet, sizeof packet, 1, out);
631 fwrite(data, len, 1, out);
636 static void logcontrol(int fd, FILE *out, int level) {
637 sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
641 while(recvline(fd, line, sizeof line)) {
643 int n = sscanf(line, "%d %d %d", &code, &req, &len);
644 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
646 if(!recvdata(fd, data, len))
648 fwrite(data, len, 1, out);
655 static bool remove_service(void) {
656 SC_HANDLE manager = NULL;
657 SC_HANDLE service = NULL;
658 SERVICE_STATUS status = {0};
660 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
662 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
666 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
669 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
673 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
674 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
676 fprintf(stderr, "%s service stopped\n", identname);
678 if(!DeleteService(service)) {
679 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
683 fprintf(stderr, "%s service removed\n", identname);
689 static bool connect_tincd(bool verbose) {
694 struct timeval tv = {0, 0};
695 if(select(fd + 1, &r, NULL, NULL, &tv)) {
696 fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
704 FILE *f = fopen(pidfilename, "r");
707 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
714 if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
716 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
724 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
726 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
731 struct addrinfo hints = {
732 .ai_family = AF_UNSPEC,
733 .ai_socktype = SOCK_STREAM,
734 .ai_protocol = IPPROTO_TCP,
738 struct addrinfo *res = NULL;
740 if(getaddrinfo(host, port, &hints, &res) || !res) {
742 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
746 fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
749 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
754 unsigned long arg = 0;
756 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
758 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
762 if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
764 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
775 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
777 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
783 sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
785 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
787 fprintf(stderr, "Could not fully establish control socket connection\n");
797 static int cmd_start(int argc, char *argv[]) {
798 if(connect_tincd(false)) {
800 fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
802 fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
807 char *slash = strrchr(program_name, '/');
810 if ((c = strrchr(program_name, '\\')) > slash)
815 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
820 char **nargv = xmalloc_and_zero((optind + argc) * sizeof *nargv);
823 for(int i = 1; i < optind; i++)
824 nargv[nargc++] = orig_argv[i];
825 for(int i = 1; i < argc; i++)
826 nargv[nargc++] = argv[i];
830 fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
835 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
841 exit(execvp(c, nargv));
846 if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
847 fprintf(stderr, "Error starting %s\n", c);
855 static int cmd_stop(int argc, char *argv[]) {
857 if(!connect_tincd(true)) {
859 if(kill(pid, SIGTERM)) {
860 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
864 fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
865 waitpid(pid, NULL, 0);
872 sendline(fd, "%d %d", CONTROL, REQ_STOP);
873 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
874 fprintf(stderr, "Could not stop tinc daemon.\n");
878 // Wait for tincd to close the connection...
882 select(fd + 1, &r, NULL, NULL, NULL);
884 if(!remove_service())
894 static int cmd_restart(int argc, char *argv[]) {
895 cmd_stop(argc, argv);
896 return cmd_start(argc, argv);
899 static int cmd_reload(int argc, char *argv[]) {
900 if(!connect_tincd(true))
903 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
904 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
905 fprintf(stderr, "Could not reload configuration.\n");
913 static int cmd_dump(int argc, char *argv[]) {
915 fprintf(stderr, "Invalid number of arguments.\n");
920 if(!connect_tincd(true))
925 if(!strcasecmp(argv[1], "nodes"))
926 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
927 else if(!strcasecmp(argv[1], "edges"))
928 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
929 else if(!strcasecmp(argv[1], "subnets"))
930 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
931 else if(!strcasecmp(argv[1], "connections"))
932 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
933 else if(!strcasecmp(argv[1], "graph")) {
934 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
935 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
937 } else if(!strcasecmp(argv[1], "digraph")) {
938 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
939 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
942 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
949 else if(do_graph == 2)
950 printf("digraph {\n");
952 while(recvline(fd, line, sizeof line)) {
953 char node1[4096], node2[4096];
954 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
956 if(do_graph && req == REQ_DUMP_NODES)
975 int cipher, digest, maclength, compression, distance, socket, weight;
976 short int pmtu, minmtu, maxmtu;
977 unsigned int options, status_int;
978 node_status_t status;
979 long int last_state_change;
982 case REQ_DUMP_NODES: {
983 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);
985 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
989 memcpy(&status, &status_int, sizeof status);
990 const char *color = "black";
991 if(!strcmp(host, "MYSELF"))
993 else if(!status.reachable)
995 else if(strcmp(via, node))
997 else if(!status.validkey)
1001 printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1003 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",
1004 node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1008 case REQ_DUMP_EDGES: {
1009 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1011 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1016 float w = 1 + 65536.0 / weight;
1017 if(do_graph == 1 && strcmp(node1, node2) > 0)
1018 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1019 else if(do_graph == 2)
1020 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1022 printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1026 case REQ_DUMP_SUBNETS: {
1027 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1029 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1032 printf("%s owner %s\n", strip_weight(subnet), node);
1035 case REQ_DUMP_CONNECTIONS: {
1036 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1038 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1041 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1045 fprintf(stderr, "Unable to parse dump from tincd.\n");
1050 fprintf(stderr, "Error receiving dump.\n");
1054 static int cmd_purge(int argc, char *argv[]) {
1055 if(!connect_tincd(true))
1058 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1059 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1060 fprintf(stderr, "Could not purge old information.\n");
1067 static int cmd_debug(int argc, char *argv[]) {
1069 fprintf(stderr, "Invalid number of arguments.\n");
1073 if(!connect_tincd(true))
1076 int debuglevel = atoi(argv[1]);
1079 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1080 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1081 fprintf(stderr, "Could not set debug level.\n");
1085 fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1089 static int cmd_retry(int argc, char *argv[]) {
1090 if(!connect_tincd(true))
1093 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1094 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1095 fprintf(stderr, "Could not retry outgoing connections.\n");
1102 static int cmd_connect(int argc, char *argv[]) {
1104 fprintf(stderr, "Invalid number of arguments.\n");
1108 if(!check_id(argv[1])) {
1109 fprintf(stderr, "Invalid name for node.\n");
1113 if(!connect_tincd(true))
1116 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1117 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1118 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1125 static int cmd_disconnect(int argc, char *argv[]) {
1127 fprintf(stderr, "Invalid number of arguments.\n");
1131 if(!check_id(argv[1])) {
1132 fprintf(stderr, "Invalid name for node.\n");
1136 if(!connect_tincd(true))
1139 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1140 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1141 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1148 static int cmd_top(int argc, char *argv[]) {
1150 if(!connect_tincd(true))
1156 fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1161 static int cmd_pcap(int argc, char *argv[]) {
1162 if(!connect_tincd(true))
1165 pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1169 static int cmd_log(int argc, char *argv[]) {
1170 if(!connect_tincd(true))
1173 logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1177 static int cmd_pid(int argc, char *argv[]) {
1178 if(!connect_tincd(true) && !pid)
1181 printf("%d\n", pid);
1185 static int rstrip(char *value) {
1186 int len = strlen(value);
1187 while(len && strchr("\t\r\n ", value[len - 1]))
1192 static char *get_my_name() {
1193 FILE *f = fopen(tinc_conf, "r");
1195 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1201 while(fgets(buf, sizeof buf, f)) {
1202 int len = strcspn(buf, "\t =");
1204 value += strspn(value, "\t ");
1207 value += strspn(value, "\t ");
1212 if(strcasecmp(buf, "Name"))
1216 return strdup(value);
1221 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1225 #define VAR_SERVER 1 /* Should be in tinc.conf */
1226 #define VAR_HOST 2 /* Can be in host config file */
1227 #define VAR_MULTIPLE 4 /* Multiple statements allowed */
1228 #define VAR_OBSOLETE 8 /* Should not be used anymore */
1233 } const variables[] = {
1234 /* Server configuration */
1235 {"AddressFamily", VAR_SERVER},
1236 {"AutoConnect", VAR_SERVER},
1237 {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1238 {"BindToInterface", VAR_SERVER},
1239 {"Broadcast", VAR_SERVER},
1240 {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1241 {"DecrementTTL", VAR_SERVER},
1242 {"Device", VAR_SERVER},
1243 {"DeviceType", VAR_SERVER},
1244 {"DirectOnly", VAR_SERVER},
1245 {"ECDSAPrivateKeyFile", VAR_SERVER},
1246 {"ExperimentalProtocol", VAR_SERVER},
1247 {"Forwarding", VAR_SERVER},
1248 {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1249 {"Hostnames", VAR_SERVER},
1250 {"IffOneQueue", VAR_SERVER},
1251 {"Interface", VAR_SERVER},
1252 {"KeyExpire", VAR_SERVER},
1253 {"LocalDiscovery", VAR_SERVER},
1254 {"MACExpire", VAR_SERVER},
1255 {"MaxOutputBufferSize", VAR_SERVER},
1256 {"MaxTimeout", VAR_SERVER},
1257 {"Mode", VAR_SERVER},
1258 {"Name", VAR_SERVER},
1259 {"PingInterval", VAR_SERVER},
1260 {"PingTimeout", VAR_SERVER},
1261 {"PriorityInheritance", VAR_SERVER},
1262 {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1263 {"PrivateKeyFile", VAR_SERVER},
1264 {"ProcessPriority", VAR_SERVER},
1265 {"Proxy", VAR_SERVER},
1266 {"ReplayWindow", VAR_SERVER},
1267 {"ScriptsExtension", VAR_SERVER},
1268 {"ScriptsInterpreter", VAR_SERVER},
1269 {"StrictSubnets", VAR_SERVER},
1270 {"TunnelServer", VAR_SERVER},
1271 {"UDPRcvBuf", VAR_SERVER},
1272 {"UDPSndBuf", VAR_SERVER},
1273 {"VDEGroup", VAR_SERVER},
1274 {"VDEPort", VAR_SERVER},
1275 /* Host configuration */
1276 {"Address", VAR_HOST | VAR_MULTIPLE},
1277 {"Cipher", VAR_SERVER | VAR_HOST},
1278 {"ClampMSS", VAR_SERVER | VAR_HOST},
1279 {"Compression", VAR_SERVER | VAR_HOST},
1280 {"Digest", VAR_SERVER | VAR_HOST},
1281 {"ECDSAPublicKey", VAR_HOST},
1282 {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1283 {"IndirectData", VAR_SERVER | VAR_HOST},
1284 {"MACLength", VAR_SERVER | VAR_HOST},
1285 {"PMTU", VAR_SERVER | VAR_HOST},
1286 {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1288 {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1289 {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1290 {"Subnet", VAR_HOST | VAR_MULTIPLE},
1291 {"TCPOnly", VAR_SERVER | VAR_HOST},
1292 {"Weight", VAR_HOST},
1296 static int cmd_config(int argc, char *argv[]) {
1298 fprintf(stderr, "Invalid number of arguments.\n");
1303 if(!strcasecmp(argv[1], "get")) {
1305 } else if(!strcasecmp(argv[1], "add")) {
1306 argv++, argc--, action = 1;
1307 } else if(!strcasecmp(argv[1], "del")) {
1308 argv++, argc--, action = -1;
1309 } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1310 argv++, argc--, action = 0;
1314 fprintf(stderr, "Invalid number of arguments.\n");
1318 // Concatenate the rest of the command line
1319 strncpy(line, argv[1], sizeof line - 1);
1320 for(int i = 2; i < argc; i++) {
1321 strncat(line, " ", sizeof line - 1 - strlen(line));
1322 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1325 // Liberal parsing into node name, variable name and value.
1331 len = strcspn(line, "\t =");
1333 value += strspn(value, "\t ");
1336 value += strspn(value, "\t ");
1339 variable = strchr(line, '.');
1348 fprintf(stderr, "No variable given.\n");
1352 if(action >= 0 && !*value) {
1353 fprintf(stderr, "No value for variable given.\n");
1357 if(action < -1 && *value)
1360 /* Some simple checks. */
1363 for(int i = 0; variables[i].name; i++) {
1364 if(strcasecmp(variables[i].name, variable))
1368 variable = (char *)variables[i].name;
1370 /* Discourage use of obsolete variables. */
1372 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1374 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1376 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1381 /* Don't put server variables in host config files */
1383 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1385 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1387 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1392 /* Should this go into our own host config file? */
1394 if(!node && !(variables[i].type & VAR_SERVER)) {
1395 node = get_my_name();
1403 if(node && !check_id(node)) {
1404 fprintf(stderr, "Invalid name for node.\n");
1409 if(force || action < 0) {
1410 fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1412 fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1417 // Open the right configuration file.
1420 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1422 filename = tinc_conf;
1424 FILE *f = fopen(filename, "r");
1426 if(action < 0 || errno != ENOENT) {
1427 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1431 // If it doesn't exist, create it.
1432 f = fopen(filename, "a+");
1434 fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1437 fprintf(stderr, "Created configuration file %s.\n", filename);
1441 char *tmpfile = NULL;
1445 xasprintf(&tmpfile, "%s.config.tmp", filename);
1446 tf = fopen(tmpfile, "w");
1448 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1454 // Copy the file, making modifications on the fly, unless we are just getting a value.
1458 bool removed = false;
1461 while(fgets(buf1, sizeof buf1, f)) {
1462 buf1[sizeof buf1 - 1] = 0;
1463 strncpy(buf2, buf1, sizeof buf2);
1465 // Parse line in a simple way
1469 len = strcspn(buf2, "\t =");
1470 bvalue = buf2 + len;
1471 bvalue += strspn(bvalue, "\t ");
1472 if(*bvalue == '=') {
1474 bvalue += strspn(bvalue, "\t ");
1480 if(!strcasecmp(buf2, variable)) {
1484 printf("%s\n", bvalue);
1486 } else if(action == -1) {
1487 if(!*value || !strcasecmp(bvalue, value)) {
1492 } else if(action == 0) {
1493 // Already set? Delete the rest...
1496 // Otherwise, replace.
1497 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1498 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1507 // Copy original line...
1508 if(fputs(buf1, tf) < 0) {
1509 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1513 // Add newline if it is missing...
1514 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1515 if(fputc('\n', tf) < 0) {
1516 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1523 // Make sure we read everything...
1524 if(ferror(f) || !feof(f)) {
1525 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1530 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1534 // Add new variable if necessary.
1535 if(action > 0 || (action == 0 && !set)) {
1536 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1537 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1544 fprintf(stderr, "No matching configuration variables found.\n");
1548 // Make sure we wrote everything...
1550 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1554 // Could we find what we had to remove?
1555 if(action < 0 && !removed) {
1557 fprintf(stderr, "No configuration variables deleted.\n");
1561 // Replace the configuration file with the new one
1563 if(remove(filename)) {
1564 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1568 if(rename(tmpfile, filename)) {
1569 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1573 // Silently try notifying a running tincd of changes.
1574 if(connect_tincd(false))
1575 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1580 bool check_id(const char *name) {
1584 for(int i = 0; i < strlen(name); i++) {
1585 if(!isalnum(name[i]) && name[i] != '_')
1592 static int cmd_init(int argc, char *argv[]) {
1593 if(!access(tinc_conf, F_OK)) {
1594 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1601 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1603 if(!fgets(buf, sizeof buf, stdin)) {
1604 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1607 int len = rstrip(buf);
1609 fprintf(stderr, "No name given!\n");
1614 fprintf(stderr, "No Name given!\n");
1618 name = strdup(argv[1]);
1620 fprintf(stderr, "No Name given!\n");
1625 if(!check_id(name)) {
1626 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1630 if(mkdir(confdir, 0755) && errno != EEXIST) {
1631 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1635 if(mkdir(confbase, 0755) && errno != EEXIST) {
1636 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1640 if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1641 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1645 FILE *f = fopen(tinc_conf, "w");
1647 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1651 fprintf(f, "Name = %s\n", name);
1654 if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1659 xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1660 if(access(filename, F_OK)) {
1661 FILE *f = fopen(filename, "w");
1663 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1666 fchmod(fileno(f), 0755);
1667 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");
1676 static int cmd_generate_keys(int argc, char *argv[]) {
1677 return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1680 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1681 return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1684 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1685 return !ecdsa_keygen(true);
1688 static int cmd_help(int argc, char *argv[]) {
1693 static int cmd_version(int argc, char *argv[]) {
1698 static int cmd_info(int argc, char *argv[]) {
1700 fprintf(stderr, "Invalid number of arguments.\n");
1704 if(!connect_tincd(true))
1707 return info(fd, argv[1]);
1710 static const char *conffiles[] = {
1721 static int cmd_edit(int argc, char *argv[]) {
1723 fprintf(stderr, "Invalid number of arguments.\n");
1727 char *filename = NULL;
1729 if(strncmp(argv[1], "hosts" SLASH, 6)) {
1730 for(int i = 0; conffiles[i]; i++) {
1731 if(!strcmp(argv[1], conffiles[i])) {
1732 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1741 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1742 char *dash = strchr(argv[1], '-');
1745 if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1746 fprintf(stderr, "Invalid configuration filename.\n");
1754 xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1756 xasprintf(&command, "edit \"%s\"", filename);
1758 int result = system(command);
1762 // Silently try notifying a running tincd of changes.
1763 if(connect_tincd(false))
1764 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1769 static int export(const char *name, FILE *out) {
1771 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1772 FILE *in = fopen(filename, "r");
1774 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1778 fprintf(out, "Name = %s\n", name);
1780 while(fgets(buf, sizeof buf, in)) {
1781 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1786 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1795 static int cmd_export(int argc, char *argv[]) {
1796 char *name = get_my_name();
1800 return export(name, stdout);
1803 static int cmd_export_all(int argc, char *argv[]) {
1804 DIR *dir = opendir(hosts_dir);
1806 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1814 while((ent = readdir(dir))) {
1815 if(!check_id(ent->d_name))
1821 printf("#---------------------------------------------------------------#\n");
1823 result |= export(ent->d_name, stdout);
1830 static int cmd_import(int argc, char *argv[]) {
1838 bool firstline = true;
1840 while(fgets(buf, sizeof buf, in)) {
1841 if(sscanf(buf, "Name = %s", name) == 1) {
1842 if(!check_id(name)) {
1843 fprintf(stderr, "Invalid Name in input!\n");
1851 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1853 if(!force && !access(filename, F_OK)) {
1854 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1859 out = fopen(filename, "w");
1861 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1868 } else if(firstline) {
1869 fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1874 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1878 if(fputs(buf, out) < 0) {
1879 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1889 fprintf(stderr, "Imported %d host configuration files.\n", count);
1892 fprintf(stderr, "No host configuration files imported.\n");
1897 static const struct {
1898 const char *command;
1899 int (*function)(int argc, char *argv[]);
1901 {"start", cmd_start},
1903 {"restart", cmd_restart},
1904 {"reload", cmd_reload},
1906 {"purge", cmd_purge},
1907 {"debug", cmd_debug},
1908 {"retry", cmd_retry},
1909 {"connect", cmd_connect},
1910 {"disconnect", cmd_disconnect},
1915 {"config", cmd_config},
1917 {"generate-keys", cmd_generate_keys},
1918 {"generate-rsa-keys", cmd_generate_rsa_keys},
1919 {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1921 {"version", cmd_version},
1924 {"export", cmd_export},
1925 {"export-all", cmd_export_all},
1926 {"import", cmd_import},
1930 #ifdef HAVE_READLINE
1931 static char *complete_command(const char *text, int state) {
1939 while(commands[i].command) {
1940 if(!strncasecmp(commands[i].command, text, strlen(text)))
1941 return xstrdup(commands[i].command);
1948 static char *complete_dump(const char *text, int state) {
1949 const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1958 if(!strncasecmp(matches[i], text, strlen(text)))
1959 return xstrdup(matches[i]);
1966 static char *complete_config(const char *text, int state) {
1967 const char *sub[] = {"get", "set", "add", "del"};
1971 if(!strchr(rl_line_buffer + 7, ' '))
1975 for(int i = 0; i < 4; i++) {
1976 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1988 while(i < 0 || variables[i].name) {
1989 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
1990 return xstrdup(sub[i + 4]);
1992 char *dot = strchr(text, '.');
1994 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
1996 xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2000 if(!strncasecmp(variables[i].name, text, strlen(text)))
2001 return xstrdup(variables[i].name);
2010 static char *complete_info(const char *text, int state) {
2014 if(!connect_tincd(false))
2016 // Check the list of nodes
2017 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2018 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2021 while(recvline(fd, line, sizeof line)) {
2023 int n = sscanf(line, "%d %d %s", &code, &req, item);
2033 fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2037 if(!strncmp(item, text, strlen(text)))
2038 return xstrdup(strip_weight(item));
2044 static char *complete_nothing(const char *text, int state) {
2048 static char **completion (const char *text, int start, int end) {
2049 char **matches = NULL;
2052 matches = rl_completion_matches(text, complete_command);
2053 else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2054 matches = rl_completion_matches(text, complete_dump);
2055 else if(!strncasecmp(rl_line_buffer, "config ", 7))
2056 matches = rl_completion_matches(text, complete_config);
2057 else if(!strncasecmp(rl_line_buffer, "info ", 5))
2058 matches = rl_completion_matches(text, complete_info);
2064 static int cmd_shell(int argc, char *argv[]) {
2066 xasprintf(&prompt, "%s> ", identname);
2070 int maxargs = argc + 16;
2071 char **nargv = xmalloc(maxargs * sizeof *nargv);
2073 for(int i = 0; i < argc; i++)
2076 #ifdef HAVE_READLINE
2077 rl_readline_name = "tinc";
2078 rl_completion_entry_function = complete_nothing;
2079 rl_attempted_completion_function = completion;
2080 rl_filename_completion_desired = 0;
2085 #ifdef HAVE_READLINE
2089 rl_basic_word_break_characters = "\t\n ";
2090 line = readline(prompt);
2092 copy = xstrdup(line);
2094 line = fgets(buf, sizeof buf, stdin);
2098 fputs(prompt, stdout);
2100 line = fgets(buf, sizeof buf, stdin);
2106 /* Ignore comments */
2114 char *p = line + strspn(line, " \t\n");
2115 char *next = strtok(p, " \t\n");
2118 if(nargc >= maxargs) {
2119 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2122 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2127 next = strtok(NULL, " \t\n");
2133 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2138 for(int i = 0; commands[i].command; i++) {
2139 if(!strcasecmp(nargv[argc], commands[i].command)) {
2140 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2146 #ifdef HAVE_READLINE
2152 fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2165 int main(int argc, char *argv[]) {
2166 program_name = argv[0];
2170 if(!parse_options(argc, argv))
2185 tty = isatty(0) && isatty(1);
2188 return cmd_shell(argc, argv);
2190 for(int i = 0; commands[i].command; i++) {
2191 if(!strcasecmp(argv[optind], commands[i].command))
2192 return commands[i].function(argc - optind, argv + optind);
2195 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);