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