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