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