Purge through the control socket
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
4
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.
9
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.
14
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.
18
19     $Id$
20 */
21
22 #include "system.h"
23
24 #include <sys/un.h>
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>
30
31 #include <getopt.h>
32
33 #include "xalloc.h"
34 #include "protocol.h"
35 #include "control_common.h"
36
37 /* The name this program was run with. */
38 char *program_name = NULL;
39
40 /* If nonzero, display usage information and exit. */
41 bool show_help = false;
42
43 /* If nonzero, print the version on standard output and exit.  */
44 bool show_version = false;
45
46 /* If nonzero, it will attempt to kill a running tincd and exit. */
47 int kill_tincd = 0;
48
49 /* If nonzero, generate public/private keypair for this host/net. */
50 int generate_keys = 0;
51
52 static char *identname = NULL;                          /* program name for syslog */
53 static char *controlsocketname = NULL;                  /* pid file location */
54 char *netname = NULL;
55 char *confbase = NULL;
56
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},
63         {NULL, 0, NULL, 0}
64 };
65
66 static void usage(bool status) {
67         if(status)
68                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
69                                 program_name);
70         else {
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"
78                                 "\n"
79                                 "Valid commands are:\n"
80                                 "  start                      Start tincd.\n"
81                                 "  stop                       Stop 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                                 "\n"));
94                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
95         }
96 }
97
98 static bool parse_options(int argc, char **argv) {
99         int r;
100         int option_index = 0;
101
102         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
103                 switch (r) {
104                         case 0:                         /* long option */
105                                 break;
106
107                         case 'c':                               /* config file */
108                                 confbase = xstrdup(optarg);
109                                 break;
110
111                         case 'n':                               /* net name given */
112                                 netname = xstrdup(optarg);
113                                 break;
114
115                         case 1:                                 /* show help */
116                                 show_help = true;
117                                 break;
118
119                         case 2:                                 /* show version */
120                                 show_version = true;
121                                 break;
122
123                         case 5:                                 /* open control socket here */
124                                 controlsocketname = xstrdup(optarg);
125                                 break;
126
127                         case '?':
128                                 usage(true);
129                                 return false;
130
131                         default:
132                                 break;
133                 }
134         }
135
136         return true;
137 }
138
139 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
140         FILE *r;
141         char *directory;
142         char buf[PATH_MAX];
143         char buf2[PATH_MAX];
144         size_t len;
145
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]: "),
150                                 what, filename);
151                 fflush(stdout);
152
153                 if(fgets(buf, sizeof buf, stdin) < 0) {
154                         fprintf(stderr, _("Error while reading stdin: %s\n"),
155                                         strerror(errno));
156                         return NULL;
157                 }
158
159                 len = strlen(buf);
160                 if(len)
161                         buf[--len] = 0;
162
163                 if(len)
164                         filename = buf;
165         }
166
167 #ifdef HAVE_MINGW
168         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
169 #else
170         if(filename[0] != '/') {
171 #endif
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);
175                 filename = buf2;
176         }
177
178         umask(0077);                            /* Disallow everything for group and other */
179
180         /* Open it first to keep the inode busy */
181
182         r = fopen(filename, mode);
183
184         if(!r) {
185                 fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
186                 return NULL;
187         }
188
189         return r;
190 }
191
192 /* This function prettyprints the key generation process */
193
194 static void indicator(int a, int b, void *p) {
195         switch (a) {
196                 case 0:
197                         fprintf(stderr, ".");
198                         break;
199
200                 case 1:
201                         fprintf(stderr, "+");
202                         break;
203
204                 case 2:
205                         fprintf(stderr, "-");
206                         break;
207
208                 case 3:
209                         switch (b) {
210                                 case 0:
211                                         fprintf(stderr, " p\n");
212                                         break;
213
214                                 case 1:
215                                         fprintf(stderr, " q\n");
216                                         break;
217
218                                 default:
219                                         fprintf(stderr, "?");
220                         }
221                         break;
222
223                 default:
224                         fprintf(stderr, "?");
225         }
226 }
227
228 /*
229   Generate a public/private RSA keypair, and ask for a file to store
230   them in.
231 */
232 static bool keygen(int bits) {
233         RSA *rsa_key;
234         FILE *f;
235         char *name = NULL;
236         char *filename;
237
238         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
239         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
240
241         if(!rsa_key) {
242                 fprintf(stderr, _("Error during key generation!\n"));
243                 return false;
244         } else
245                 fprintf(stderr, _("Done.\n"));
246
247         asprintf(&filename, "%s/rsa_key.priv", confbase);
248         f = ask_and_open(filename, _("private RSA key"), "a");
249
250         if(!f)
251                 return false;
252   
253 #ifdef HAVE_FCHMOD
254         /* Make it unreadable for others. */
255         fchmod(fileno(f), 0600);
256 #endif
257                 
258         if(ftell(f))
259                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
260
261         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
262         fclose(f);
263         free(filename);
264
265         if(name)
266                 asprintf(&filename, "%s/hosts/%s", confbase, name);
267         else
268                 asprintf(&filename, "%s/rsa_key.pub", confbase);
269
270         f = ask_and_open(filename, _("public RSA key"), "a");
271
272         if(!f)
273                 return false;
274
275         if(ftell(f))
276                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
277
278         PEM_write_RSAPublicKey(f, rsa_key);
279         fclose(f);
280         free(filename);
281
282         return true;
283 }
284
285 /*
286   Set all files and paths according to netname
287 */
288 static void make_names(void) {
289 #ifdef HAVE_MINGW
290         HKEY key;
291         char installdir[1024] = "";
292         long len = sizeof(installdir);
293 #endif
294
295         if(netname)
296                 asprintf(&identname, "tinc.%s", netname);
297         else
298                 identname = xstrdup("tinc");
299
300 #ifdef HAVE_MINGW
301         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
302                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
303                         if(!logfilename)
304                                 asprintf(&logfilename, "%s/log/%s.log", identname);
305                         if(!confbase) {
306                                 if(netname)
307                                         asprintf(&confbase, "%s/%s", installdir, netname);
308                                 else
309                                         asprintf(&confbase, "%s", installdir);
310                         }
311                 }
312                 RegCloseKey(key);
313                 if(*installdir)
314                         return;
315         }
316 #endif
317
318         if(!controlsocketname)
319                 asprintf(&controlsocketname, LOCALSTATEDIR "/run/%s.control", identname);
320
321         if(netname) {
322                 if(!confbase)
323                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
324                 else
325                         fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
326         } else {
327                 if(!confbase)
328                         asprintf(&confbase, CONFDIR "/tinc");
329         }
330 }
331
332 static int fullread(int fd, void *data, size_t datalen) {
333         int rv, len = 0;
334
335         while (len < datalen) {
336                 rv = read(fd, data + len, datalen - len);
337                 if(rv == -1 && errno == EINTR)
338                         continue;
339                 else if (rv == -1)
340                         return rv;
341                 else if (rv == 0) {
342                         errno = ENODATA;
343                         return -1;
344                 }
345                 len += rv;
346         }
347         return 0;
348 }
349
350 /*
351    Send a request (raw)
352 */
353 static int send_ctl_request(int fd, enum request_type type,
354                                                    void const *outdata, size_t outdatalen,
355                                                    int *res_errno_p, void **indata_p,
356                                                    size_t *indatalen_p) {
357         tinc_ctl_request_t req;
358         int rv;
359         struct iovec vector[2] = {
360                 {&req, sizeof(req)},
361                 {(void*) outdata, outdatalen}
362         };
363         void *indata;
364
365         if(res_errno_p == NULL)
366                 return -1;
367
368         memset(&req, 0, sizeof req);
369         req.length = sizeof req + outdatalen;
370         req.type = type;
371         req.res_errno = 0;
372
373         while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
374         if(rv != req.length)
375                 return -1;
376
377         if(fullread(fd, &req, sizeof req) == -1)
378                 return -1;
379
380         if(req.length < sizeof req) {
381                 errno = EINVAL;
382                 return -1;
383         }
384
385         if(req.length > sizeof req) {
386                 if (indata_p == NULL) {
387                         errno = EINVAL;
388                         return -1;
389                 }
390
391                 indata = xmalloc(req.length - sizeof req);
392
393                 if(fullread(fd, indata, req.length - sizeof req) == -1) {
394                         free(indata);
395                         return -1;
396                 }
397
398                 *indata_p = indata;
399                 if(indatalen_p != NULL)
400                         *indatalen_p = req.length - sizeof req;
401         }
402
403         *res_errno_p = req.res_errno;
404
405         return 0;
406 }
407
408 /*
409    Send a request (with printfs)
410 */
411 static int send_ctl_request_cooked(int fd, enum request_type type,
412                                                                    void const *outdata, size_t outdatalen)
413 {
414         int res_errno = -1;
415         char *buf = NULL;
416         size_t buflen = 0;
417
418         if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
419                                                 (void**) &buf, &buflen)) {
420                 fprintf(stderr, _("Error sending request: %s\n"), strerror(errno));
421                 return -1;
422         }
423
424         if(buf != NULL) {
425                 printf("%*s", buflen, buf);
426                 free(buf);
427         }
428
429         if(res_errno != 0) {
430                 fprintf(stderr, _("Server reported error: %s\n"), strerror(res_errno));
431                 return -1;
432         }
433
434         return 0;
435 }
436
437 int main(int argc, char *argv[], char *envp[]) {
438         struct sockaddr_un addr;
439         int fd;
440         int len;
441         tinc_ctl_greeting_t greeting;
442         tinc_ctl_request_t req;
443
444         program_name = argv[0];
445
446         setlocale(LC_ALL, "");
447         bindtextdomain(PACKAGE, LOCALEDIR);
448         textdomain(PACKAGE);
449
450         if(!parse_options(argc, argv))
451                 return 1;
452         
453         make_names();
454
455         if(show_version) {
456                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
457                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
458                 printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
459                                 "See the AUTHORS file for a complete list.\n\n"
460                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
461                                 "and you are welcome to redistribute it under certain conditions;\n"
462                                 "see the file COPYING for details.\n"));
463
464                 return 0;
465         }
466
467         if(show_help) {
468                 usage(false);
469                 return 0;
470         }
471
472         if(optind >= argc) {
473                 fprintf(stderr, _("Not enough arguments.\n"));
474                 usage(true);
475                 return 1;
476         }
477
478         // First handle commands that don't involve connecting to a running tinc daemon.
479
480         if(!strcasecmp(argv[optind], "generate-keys")) {
481                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
482         }
483
484         if(!strcasecmp(argv[optind], "start")) {
485                 argv[optind] = NULL;
486                 execve("tincd", argv, envp);
487                 fprintf(stderr, _("Could not start tincd: %s"), strerror(errno));
488                 return 1;
489         }
490
491         // Now handle commands that do involve connecting to a running tinc daemon.
492
493         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
494                 fprintf(stderr, _("Control socket filename too long!\n"));
495                 return 1;
496         }
497
498         fd = socket(PF_UNIX, SOCK_STREAM, 0);
499         if(fd < 0) {
500                 fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
501                 return 1;
502         }
503
504         memset(&addr, 0, sizeof addr);
505         addr.sun_family = AF_UNIX;
506         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
507
508         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
509                 fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
510                 return 1;
511         }
512
513         if(fullread(fd, &greeting, sizeof greeting) == -1) {
514                 fprintf(stderr, _("Cannot read greeting from control socket: %s\n"),
515                                 strerror(errno));
516                 return 1;
517         }
518
519         if(greeting.version != TINC_CTL_VERSION_CURRENT) {
520                 fprintf(stderr, _("Version mismatch: server %d, client %d\n"),
521                                 greeting.version, TINC_CTL_VERSION_CURRENT);
522                 return 1;
523         }
524
525         struct ucred cred;
526         socklen_t credlen = sizeof cred;
527
528         if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &credlen) < 0) {
529                 fprintf(stderr, _("Could not obtain PID: %s\n"), strerror(errno));
530                 return 1;
531         }
532
533         if(!strcasecmp(argv[optind], "pid")) {
534                 printf("%d\n", cred.pid);
535                 return 0;
536         }
537
538         if(!strcasecmp(argv[optind], "stop")) {
539                 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
540         }
541
542         if(!strcasecmp(argv[optind], "reload")) {
543                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
544         }
545         
546         if(!strcasecmp(argv[optind], "restart")) {
547                 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
548         }
549
550         if(!strcasecmp(argv[optind], "dump")) {
551                 if (argc < optind + 2) {
552                         fprintf(stderr, _("Not enough arguments.\n"));
553                         usage(true);
554                         return 1;
555                 }
556
557                 if(!strcasecmp(argv[optind+1], "nodes")) {
558                         return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
559                 }
560
561                 if(!strcasecmp(argv[optind+1], "edges")) {
562                         return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
563                 }
564
565                 if(!strcasecmp(argv[optind+1], "subnets")) {
566                         return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
567                 }
568
569                 if(!strcasecmp(argv[optind+1], "connections")) {
570                         return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
571                 }
572
573                 if(!strcasecmp(argv[optind+1], "graph")) {
574                         return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
575                 }
576
577                 fprintf(stderr, _("Unknown dump type '%s'.\n"), argv[optind+1]);
578                 usage(true);
579                 return 1;
580         }
581
582         if(!strcasecmp(argv[optind], "purge")) {
583                 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
584         }
585
586         fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]);
587         usage(true);
588         
589         close(fd);
590
591         return 0;
592 }