2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007-2009 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"
30 /* The name this program was run with. */
31 char *program_name = NULL;
33 /* If nonzero, display usage information and exit. */
34 bool show_help = false;
36 /* If nonzero, print the version on standard output and exit. */
37 bool show_version = false;
39 /* If nonzero, it will attempt to kill a running tincd and exit. */
42 /* If nonzero, generate public/private keypair for this host/net. */
43 int generate_keys = 0;
45 static char *identname = NULL; /* program name for syslog */
46 static char *controlsocketname = NULL; /* pid file location */
48 char *confbase = NULL;
51 static struct WSAData wsa_state;
54 static struct option const long_options[] = {
55 {"config", required_argument, NULL, 'c'},
56 {"net", required_argument, NULL, 'n'},
57 {"help", no_argument, NULL, 1},
58 {"version", no_argument, NULL, 2},
59 {"controlsocket", required_argument, NULL, 5},
63 static void usage(bool status) {
65 fprintf(stderr, "Try `%s --help\' for more information.\n",
68 printf("Usage: %s [options] command\n\n", program_name);
69 printf("Valid options are:\n"
70 " -c, --config=DIR Read configuration options from DIR.\n"
71 " -n, --net=NETNAME Connect to net NETNAME.\n"
72 " --controlsocket=FILENAME Open control socket at FILENAME.\n"
73 " --help Display this help and exit.\n"
74 " --version Output version information and exit.\n"
76 "Valid commands are:\n"
77 " start Start tincd.\n"
79 " restart Restart tincd.\n"
80 " reload Reload configuration of running tincd.\n"
81 " pid Show PID of currently running tincd.\n"
82 " generate-keys [bits] Generate a new public/private keypair.\n"
83 " dump Dump a list of one of the following things:\n"
84 " nodes - all known nodes in the VPN\n"
85 " edges - all known connections in the VPN\n"
86 " subnets - all known subnets in the VPN\n"
87 " connections - all meta connections with ourself\n"
88 " graph - graph of the VPN in dotty format\n"
89 " purge Purge unreachable nodes\n"
90 " debug N Set debug level\n"
91 " retry Retry all outgoing connections\n"
92 " reload Partial reload of configuration\n"
94 printf("Report bugs to tinc@tinc-vpn.org.\n");
98 static bool parse_options(int argc, char **argv) {
100 int option_index = 0;
102 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
104 case 0: /* long option */
107 case 'c': /* config file */
108 confbase = xstrdup(optarg);
111 case 'n': /* net name given */
112 netname = xstrdup(optarg);
115 case 1: /* show help */
119 case 2: /* show version */
123 case 5: /* open control socket here */
124 controlsocketname = xstrdup(optarg);
139 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
146 /* Check stdin and stdout */
147 if(isatty(0) && isatty(1)) {
148 /* Ask for a file and/or directory name. */
149 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
153 if(fgets(buf, sizeof buf, stdin) < 0) {
154 fprintf(stderr, "Error while reading stdin: %s\n",
168 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
170 if(filename[0] != '/') {
172 /* The directory is a relative path or a filename. */
173 directory = get_current_dir_name();
174 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
178 umask(0077); /* Disallow everything for group and other */
180 /* Open it first to keep the inode busy */
182 r = fopen(filename, mode);
185 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
193 Generate a public/private RSA keypair, and ask for a file to store
196 static bool keygen(int bits) {
202 fprintf(stderr, "Generating %d bits keys:\n", bits);
204 if(!rsa_generate(&key, bits, 0x10001)) {
205 fprintf(stderr, "Error during key generation!\n");
208 fprintf(stderr, "Done.\n");
210 xasprintf(&filename, "%s/rsa_key.priv", confbase);
211 f = ask_and_open(filename, "private RSA key", "a");
217 /* Make it unreadable for others. */
218 fchmod(fileno(f), 0600);
222 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
224 rsa_write_pem_private_key(&key, f);
230 xasprintf(&filename, "%s/hosts/%s", confbase, name);
232 xasprintf(&filename, "%s/rsa_key.pub", confbase);
234 f = ask_and_open(filename, "public RSA key", "a");
240 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
242 rsa_write_pem_public_key(&key, f);
251 Set all files and paths according to netname
253 static void make_names(void) {
256 char installdir[1024] = "";
257 long len = sizeof installdir;
261 xasprintf(&identname, "tinc.%s", netname);
263 identname = xstrdup("tinc");
266 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
267 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
270 xasprintf(&confbase, "%s/%s", installdir, netname);
272 xasprintf(&confbase, "%s", installdir);
281 if(!controlsocketname)
282 xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
286 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
288 fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
291 xasprintf(&confbase, CONFDIR "/tinc");
295 static int fullread(int fd, void *data, size_t datalen) {
298 while(len < datalen) {
299 rv = recv(fd, data + len, datalen - len, 0);
300 if(rv == -1 && errno == EINTR)
320 static int send_ctl_request(int fd, enum request_type type,
321 void const *outdata, size_t outdatalen,
322 int *res_errno_p, void **indata_p,
323 size_t *indatalen_p) {
324 tinc_ctl_request_t req;
328 memset(&req, 0, sizeof req);
329 req.length = sizeof req + outdatalen;
334 if(send(fd, (void *)&req, sizeof req, 0) != sizeof req || send(fd, outdata, outdatalen, 0) != outdatalen)
337 struct iovec vector[2] = {
339 {(void*) outdata, outdatalen}
342 if(res_errno_p == NULL)
345 while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
350 if(fullread(fd, &req, sizeof req) == -1)
353 if(req.length < sizeof req) {
358 if(req.length > sizeof req) {
359 if(indata_p == NULL) {
364 indata = xmalloc(req.length - sizeof req);
366 if(fullread(fd, indata, req.length - sizeof req) == -1) {
372 if(indatalen_p != NULL)
373 *indatalen_p = req.length - sizeof req;
376 *res_errno_p = req.res_errno;
382 Send a request (with printfs)
384 static int send_ctl_request_cooked(int fd, enum request_type type, void const *outdata, size_t outdatalen) {
389 if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
390 (void**) &buf, &buflen)) {
391 fprintf(stderr, "Error sending request: %s\n", strerror(errno));
396 printf("%*s", (int)buflen, buf);
401 fprintf(stderr, "Server reported error: %s\n", strerror(res_errno));
408 int main(int argc, char *argv[], char *envp[]) {
409 tinc_ctl_greeting_t greeting;
413 program_name = argv[0];
415 if(!parse_options(argc, argv))
421 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
422 VERSION, __DATE__, __TIME__, PROT_CURRENT);
423 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
424 "See the AUTHORS file for a complete list.\n\n"
425 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
426 "and you are welcome to redistribute it under certain conditions;\n"
427 "see the file COPYING for details.\n");
438 fprintf(stderr, "Not enough arguments.\n");
443 // First handle commands that don't involve connecting to a running tinc daemon.
445 if(!strcasecmp(argv[optind], "generate-keys")) {
446 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
449 if(!strcasecmp(argv[optind], "start")) {
451 execve(SBINDIR "/tincd", argv, envp);
452 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
457 * Now handle commands that do involve connecting to a running tinc daemon.
458 * Authenticate the server by ensuring the parent directory can be
459 * traversed only by root. Note this is not totally race-free unless all
460 * ancestors are writable only by trusted users, which we don't verify.
464 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
465 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
469 struct sockaddr_in addr;
470 memset(&addr, 0, sizeof addr);
471 addr.sin_family = AF_INET;
472 addr.sin_addr.s_addr = htonl(0x7f000001);
473 addr.sin_port = htons(55555);
475 fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
477 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
481 unsigned long arg = 0;
483 if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
484 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
487 struct sockaddr_un addr;
489 char *lastslash = strrchr(controlsocketname, '/');
490 if(lastslash != NULL) {
491 /* control socket is not in cwd; stat its parent */
493 result = stat(controlsocketname, &statbuf);
496 result = stat(".", &statbuf);
499 fprintf(stderr, "Unable to check control socket directory permissions: %s\n", strerror(errno));
503 if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
504 fprintf(stderr, "Insecure permissions on control socket directory\n");
508 if(strlen(controlsocketname) >= sizeof addr.sun_path) {
509 fprintf(stderr, "Control socket filename too long!\n");
513 fd = socket(PF_UNIX, SOCK_STREAM, 0);
515 fprintf(stderr, "Cannot create UNIX socket: %s\n", strerror(errno));
519 memset(&addr, 0, sizeof addr);
520 addr.sun_family = AF_UNIX;
521 strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
524 if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
526 fprintf(stderr, "Cannot connect to %s: %s\n", controlsocketname, sockstrerror(sockerrno));
530 if(fullread(fd, &greeting, sizeof greeting) == -1) {
531 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
532 sockstrerror(sockerrno));
536 if(greeting.version != TINC_CTL_VERSION_CURRENT) {
537 fprintf(stderr, "Version mismatch: server %d, client %d\n",
538 greeting.version, TINC_CTL_VERSION_CURRENT);
542 if(!strcasecmp(argv[optind], "pid")) {
543 printf("%d\n", greeting.pid);
547 if(!strcasecmp(argv[optind], "stop")) {
548 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
551 if(!strcasecmp(argv[optind], "reload")) {
552 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
555 if(!strcasecmp(argv[optind], "restart")) {
556 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
559 if(!strcasecmp(argv[optind], "dump")) {
560 if(argc < optind + 2) {
561 fprintf(stderr, "Not enough arguments.\n");
566 if(!strcasecmp(argv[optind+1], "nodes")) {
567 return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
570 if(!strcasecmp(argv[optind+1], "edges")) {
571 return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
574 if(!strcasecmp(argv[optind+1], "subnets")) {
575 return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
578 if(!strcasecmp(argv[optind+1], "connections")) {
579 return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
582 if(!strcasecmp(argv[optind+1], "graph")) {
583 return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
586 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
591 if(!strcasecmp(argv[optind], "purge")) {
592 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
595 if(!strcasecmp(argv[optind], "debug")) {
598 if(argc != optind + 2) {
599 fprintf(stderr, "Invalid arguments.\n");
602 debuglevel = atoi(argv[optind+1]);
603 return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
604 sizeof debuglevel) != -1;
607 if(!strcasecmp(argv[optind], "retry")) {
608 return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
611 if(!strcasecmp(argv[optind], "reload")) {
612 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
615 fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);