2 tincctl.c -- Controlling a running tincd
3 Copyright (C) 2007 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
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include <openssl/rand.h>
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/evp.h>
29 #include <openssl/engine.h>
35 #include "control_common.h"
37 /* The name this program was run with. */
38 char *program_name = NULL;
40 /* If nonzero, display usage information and exit. */
41 bool show_help = false;
43 /* If nonzero, print the version on standard output and exit. */
44 bool show_version = false;
46 /* If nonzero, it will attempt to kill a running tincd and exit. */
49 /* If nonzero, generate public/private keypair for this host/net. */
50 int generate_keys = 0;
52 static char *identname = NULL; /* program name for syslog */
53 static char *controlsocketname = NULL; /* pid file location */
55 char *confbase = NULL;
57 static struct option const long_options[] = {
58 {"config", required_argument, NULL, 'c'},
59 {"net", required_argument, NULL, 'n'},
60 {"help", no_argument, NULL, 1},
61 {"version", no_argument, NULL, 2},
62 {"controlsocket", required_argument, NULL, 5},
66 static void usage(bool status) {
68 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
71 printf(_("Usage: %s [options] command\n\n"), program_name);
72 printf(_("Valid options are:\n"
73 " -c, --config=DIR Read configuration options from DIR.\n"
74 " -n, --net=NETNAME Connect to net NETNAME.\n"
75 " --controlsocket=FILENAME Open control socket at FILENAME.\n"
76 " --help Display this help and exit.\n"
77 " --version Output version information and exit.\n"
79 "Valid commands are:\n"
80 " start Start tincd.\n"
82 " restart Restart tincd.\n"
83 " reload Reload configuration of running tincd.\n"
84 " pid Show PID of currently running tincd.\n"
85 " generate-keys [bits] Generate a new public/private keypair.\n"
86 " dump Dump a list of one of the following things:\n"
87 " nodes - all known nodes in the VPN\n"
88 " edges - all known connections in the VPN\n"
89 " subnets - all known subnets in the VPN\n"
90 " connections - all meta connections with ourself\n"
91 " graph - graph of the VPN in dotty format\n"
92 " purge Purge unreachable nodes\n"
93 " debug N Set debug level\n"
94 " retry Retry all outgoing connections\n"
95 " reload Partial reload of configuration\n"
97 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
101 static bool parse_options(int argc, char **argv) {
103 int option_index = 0;
105 while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
107 case 0: /* long option */
110 case 'c': /* config file */
111 confbase = xstrdup(optarg);
114 case 'n': /* net name given */
115 netname = xstrdup(optarg);
118 case 1: /* show help */
122 case 2: /* show version */
126 case 5: /* open control socket here */
127 controlsocketname = xstrdup(optarg);
142 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
149 /* Check stdin and stdout */
150 if(isatty(0) && isatty(1)) {
151 /* Ask for a file and/or directory name. */
152 fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
156 if(fgets(buf, sizeof buf, stdin) < 0) {
157 fprintf(stderr, _("Error while reading stdin: %s\n"),
171 if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
173 if(filename[0] != '/') {
175 /* The directory is a relative path or a filename. */
176 directory = get_current_dir_name();
177 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
181 umask(0077); /* Disallow everything for group and other */
183 /* Open it first to keep the inode busy */
185 r = fopen(filename, mode);
188 fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
195 /* This function prettyprints the key generation process */
197 static void indicator(int a, int b, void *p) {
200 fprintf(stderr, ".");
204 fprintf(stderr, "+");
208 fprintf(stderr, "-");
214 fprintf(stderr, " p\n");
218 fprintf(stderr, " q\n");
222 fprintf(stderr, "?");
227 fprintf(stderr, "?");
232 Generate a public/private RSA keypair, and ask for a file to store
235 static bool keygen(int bits) {
241 fprintf(stderr, _("Generating %d bits keys:\n"), bits);
242 rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
245 fprintf(stderr, _("Error during key generation!\n"));
248 fprintf(stderr, _("Done.\n"));
250 asprintf(&filename, "%s/rsa_key.priv", confbase);
251 f = ask_and_open(filename, _("private RSA key"), "a");
257 /* Make it unreadable for others. */
258 fchmod(fileno(f), 0600);
262 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
264 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
269 asprintf(&filename, "%s/hosts/%s", confbase, name);
271 asprintf(&filename, "%s/rsa_key.pub", confbase);
273 f = ask_and_open(filename, _("public RSA key"), "a");
279 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
281 PEM_write_RSAPublicKey(f, rsa_key);
289 Set all files and paths according to netname
291 static void make_names(void) {
294 char installdir[1024] = "";
295 long len = sizeof installdir;
299 asprintf(&identname, "tinc.%s", netname);
301 identname = xstrdup("tinc");
304 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
305 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
307 asprintf(&logfilename, "%s/log/%s.log", identname);
310 asprintf(&confbase, "%s/%s", installdir, netname);
312 asprintf(&confbase, "%s", installdir);
321 if(!controlsocketname)
322 asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
326 asprintf(&confbase, CONFDIR "/tinc/%s", netname);
328 fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
331 asprintf(&confbase, CONFDIR "/tinc");
335 static int fullread(int fd, void *data, size_t datalen) {
338 while(len < datalen) {
339 rv = read(fd, data + len, datalen - len);
340 if(rv == -1 && errno == EINTR)
356 static int send_ctl_request(int fd, enum request_type type,
357 void const *outdata, size_t outdatalen,
358 int *res_errno_p, void **indata_p,
359 size_t *indatalen_p) {
360 tinc_ctl_request_t req;
362 struct iovec vector[2] = {
364 {(void*) outdata, outdatalen}
368 if(res_errno_p == NULL)
371 memset(&req, 0, sizeof req);
372 req.length = sizeof req + outdatalen;
376 while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
380 if(fullread(fd, &req, sizeof req) == -1)
383 if(req.length < sizeof req) {
388 if(req.length > sizeof req) {
389 if(indata_p == NULL) {
394 indata = xmalloc(req.length - sizeof req);
396 if(fullread(fd, indata, req.length - sizeof req) == -1) {
402 if(indatalen_p != NULL)
403 *indatalen_p = req.length - sizeof req;
406 *res_errno_p = req.res_errno;
412 Send a request (with printfs)
414 static int send_ctl_request_cooked(int fd, enum request_type type,
415 void const *outdata, size_t outdatalen)
421 if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
422 (void**) &buf, &buflen)) {
423 fprintf(stderr, _("Error sending request: %s\n"), strerror(errno));
428 printf("%*s", buflen, buf);
433 fprintf(stderr, _("Server reported error: %s\n"), strerror(res_errno));
440 int main(int argc, char *argv[], char *envp[]) {
441 struct sockaddr_un addr;
442 tinc_ctl_greeting_t greeting;
446 program_name = argv[0];
448 setlocale(LC_ALL, "");
449 bindtextdomain(PACKAGE, LOCALEDIR);
452 if(!parse_options(argc, argv))
458 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
459 VERSION, __DATE__, __TIME__, PROT_CURRENT);
460 printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
461 "See the AUTHORS file for a complete list.\n\n"
462 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
463 "and you are welcome to redistribute it under certain conditions;\n"
464 "see the file COPYING for details.\n"));
475 fprintf(stderr, _("Not enough arguments.\n"));
480 // First handle commands that don't involve connecting to a running tinc daemon.
482 if(!strcasecmp(argv[optind], "generate-keys")) {
483 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
486 if(!strcasecmp(argv[optind], "start")) {
488 execve(SBINDIR "/tincd", argv, envp);
489 fprintf(stderr, _("Could not start tincd: %s"), strerror(errno));
494 * Now handle commands that do involve connecting to a running tinc daemon.
495 * Authenticate the server by ensuring the parent directory can be
496 * traversed only by root. Note this is not totally race-free unless all
497 * ancestors are writable only by trusted users, which we don't verify.
501 char *lastslash = strrchr(controlsocketname, '/');
502 if(lastslash != NULL) {
503 /* control socket is not in cwd; stat its parent */
505 result = stat(controlsocketname, &statbuf);
508 result = stat(".", &statbuf);
511 fprintf(stderr, _("Unable to check control socket directory permissions: %s\n"), strerror(errno));
515 if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
516 fprintf(stderr, _("Insecure permissions on control socket directory\n"));
520 if(strlen(controlsocketname) >= sizeof addr.sun_path) {
521 fprintf(stderr, _("Control socket filename too long!\n"));
525 fd = socket(PF_UNIX, SOCK_STREAM, 0);
527 fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
531 memset(&addr, 0, sizeof addr);
532 addr.sun_family = AF_UNIX;
533 strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
535 if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
536 fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
540 if(fullread(fd, &greeting, sizeof greeting) == -1) {
541 fprintf(stderr, _("Cannot read greeting from control socket: %s\n"),
546 if(greeting.version != TINC_CTL_VERSION_CURRENT) {
547 fprintf(stderr, _("Version mismatch: server %d, client %d\n"),
548 greeting.version, TINC_CTL_VERSION_CURRENT);
552 if(!strcasecmp(argv[optind], "pid")) {
553 printf("%d\n", greeting.pid);
557 if(!strcasecmp(argv[optind], "stop")) {
558 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
561 if(!strcasecmp(argv[optind], "reload")) {
562 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
565 if(!strcasecmp(argv[optind], "restart")) {
566 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
569 if(!strcasecmp(argv[optind], "dump")) {
570 if(argc < optind + 2) {
571 fprintf(stderr, _("Not enough arguments.\n"));
576 if(!strcasecmp(argv[optind+1], "nodes")) {
577 return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
580 if(!strcasecmp(argv[optind+1], "edges")) {
581 return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
584 if(!strcasecmp(argv[optind+1], "subnets")) {
585 return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
588 if(!strcasecmp(argv[optind+1], "connections")) {
589 return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
592 if(!strcasecmp(argv[optind+1], "graph")) {
593 return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
596 fprintf(stderr, _("Unknown dump type '%s'.\n"), argv[optind+1]);
601 if(!strcasecmp(argv[optind], "purge")) {
602 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
605 if(!strcasecmp(argv[optind], "debug")) {
608 if(argc != optind + 2) {
609 fprintf(stderr, "Invalid arguments.\n");
612 debuglevel = atoi(argv[optind+1]);
613 return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
614 sizeof debuglevel) != -1;
617 if(!strcasecmp(argv[optind], "retry")) {
618 return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
621 if(!strcasecmp(argv[optind], "reload")) {
622 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
625 fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]);