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