Add a very primitive "top" command to tincctl.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2011 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 along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <getopt.h>
23
24 #include "xalloc.h"
25 #include "protocol.h"
26 #include "control_common.h"
27 #include "rsagen.h"
28 #include "utils.h"
29 #include "tincctl.h"
30 #include "top.h"
31
32 /* The name this program was run with. */
33 char *program_name = NULL;
34
35 /* If nonzero, display usage information and exit. */
36 bool show_help = false;
37
38 /* If nonzero, print the version on standard output and exit.  */
39 bool show_version = false;
40
41 /* If nonzero, it will attempt to kill a running tincd and exit. */
42 int kill_tincd = 0;
43
44 /* If nonzero, generate public/private keypair for this host/net. */
45 int generate_keys = 0;
46
47 static char *name = NULL;
48 static char *identname = NULL;                          /* program name for syslog */
49 static char *controlcookiename = NULL;                  /* cookie file location */
50 static char controlcookie[1024];
51 char *netname = NULL;
52 char *confbase = NULL;
53
54 #ifdef HAVE_MINGW
55 static struct WSAData wsa_state;
56 #endif
57
58 static struct option const long_options[] = {
59         {"config", required_argument, NULL, 'c'},
60         {"net", required_argument, NULL, 'n'},
61         {"help", no_argument, NULL, 1},
62         {"version", no_argument, NULL, 2},
63         {"controlcookie", required_argument, NULL, 5},
64         {NULL, 0, NULL, 0}
65 };
66
67 static void usage(bool status) {
68         if(status)
69                 fprintf(stderr, "Try `%s --help\' for more information.\n",
70                                 program_name);
71         else {
72                 printf("Usage: %s [options] command\n\n", program_name);
73                 printf("Valid options are:\n"
74                                 "  -c, --config=DIR              Read configuration options from DIR.\n"
75                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
76                                 "      --controlcookie=FILENAME  Read control socket from FILENAME.\n"
77                                 "      --help                    Display this help and exit.\n"
78                                 "      --version                 Output version information and exit.\n"
79                                 "\n"
80                                 "Valid commands are:\n"
81                                 "  start                      Start tincd.\n"
82                                 "  stop                       Stop tincd.\n"
83                                 "  restart                    Restart tincd.\n"
84                                 "  reload                     Reload configuration of running tincd.\n"
85                                 "  pid                        Show PID of currently running tincd.\n"
86                                 "  generate-keys [bits]       Generate a new public/private keypair.\n"
87                                 "  dump                       Dump a list of one of the following things:\n"
88                                 "    nodes                    - all known nodes in the VPN\n"
89                                 "    edges                    - all known connections in the VPN\n"
90                                 "    subnets                  - all known subnets in the VPN\n"
91                                 "    connections              - all meta connections with ourself\n"
92                                 "    graph                    - graph of the VPN in dotty format\n"
93                                 "  purge                      Purge unreachable nodes\n"
94                                 "  debug N                    Set debug level\n"
95                                 "  retry                      Retry all outgoing connections\n"
96                                 "  reload                     Partial reload of configuration\n"
97                                 "  disconnect NODE            Close meta connection with NODE\n"
98 #ifdef HAVE_CURSES
99                                 "  top                        Show real-time statistics\n"
100 #endif
101                                 "\n");
102                 printf("Report bugs to tinc@tinc-vpn.org.\n");
103         }
104 }
105
106 static bool parse_options(int argc, char **argv) {
107         int r;
108         int option_index = 0;
109
110         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
111                 switch (r) {
112                         case 0:                         /* long option */
113                                 break;
114
115                         case 'c':                               /* config file */
116                                 confbase = xstrdup(optarg);
117                                 break;
118
119                         case 'n':                               /* net name given */
120                                 netname = xstrdup(optarg);
121                                 break;
122
123                         case 1:                                 /* show help */
124                                 show_help = true;
125                                 break;
126
127                         case 2:                                 /* show version */
128                                 show_version = true;
129                                 break;
130
131                         case 5:                                 /* open control socket here */
132                                 controlcookiename = xstrdup(optarg);
133                                 break;
134
135                         case '?':
136                                 usage(true);
137                                 return false;
138
139                         default:
140                                 break;
141                 }
142         }
143
144         return true;
145 }
146
147 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
148         FILE *r;
149         char *directory;
150         char buf[PATH_MAX];
151         char buf2[PATH_MAX];
152         size_t len;
153
154         /* Check stdin and stdout */
155         if(isatty(0) && isatty(1)) {
156                 /* Ask for a file and/or directory name. */
157                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
158                                 what, filename);
159                 fflush(stdout);
160
161                 if(fgets(buf, sizeof buf, stdin) < 0) {
162                         fprintf(stderr, "Error while reading stdin: %s\n",
163                                         strerror(errno));
164                         return NULL;
165                 }
166
167                 len = strlen(buf);
168                 if(len)
169                         buf[--len] = 0;
170
171                 if(len)
172                         filename = buf;
173         }
174
175 #ifdef HAVE_MINGW
176         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
177 #else
178         if(filename[0] != '/') {
179 #endif
180                 /* The directory is a relative path or a filename. */
181                 directory = get_current_dir_name();
182                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
183                 filename = buf2;
184         }
185
186         umask(0077);                            /* Disallow everything for group and other */
187
188         /* Open it first to keep the inode busy */
189
190         r = fopen(filename, mode);
191
192         if(!r) {
193                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
194                 return NULL;
195         }
196
197         return r;
198 }
199
200 /*
201   Generate a public/private RSA keypair, and ask for a file to store
202   them in.
203 */
204 static bool keygen(int bits) {
205         rsa_t key;
206         FILE *f;
207         char *filename;
208
209         fprintf(stderr, "Generating %d bits keys:\n", bits);
210
211         if(!rsa_generate(&key, bits, 0x10001)) {
212                 fprintf(stderr, "Error during key generation!\n");
213                 return false;
214         } else
215                 fprintf(stderr, "Done.\n");
216
217         xasprintf(&filename, "%s/rsa_key.priv", confbase);
218         f = ask_and_open(filename, "private RSA key", "a");
219
220         if(!f)
221                 return false;
222   
223 #ifdef HAVE_FCHMOD
224         /* Make it unreadable for others. */
225         fchmod(fileno(f), 0600);
226 #endif
227                 
228         if(ftell(f))
229                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
230
231         rsa_write_pem_private_key(&key, f);
232
233         fclose(f);
234         free(filename);
235
236         if(name)
237                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
238         else
239                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
240
241         f = ask_and_open(filename, "public RSA key", "a");
242
243         if(!f)
244                 return false;
245
246         if(ftell(f))
247                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
248
249         rsa_write_pem_public_key(&key, f);
250
251         fclose(f);
252         free(filename);
253
254         return true;
255 }
256
257 /*
258   Set all files and paths according to netname
259 */
260 static void make_names(void) {
261 #ifdef HAVE_MINGW
262         HKEY key;
263         char installdir[1024] = "";
264         long len = sizeof installdir;
265 #endif
266
267         if(netname)
268                 xasprintf(&identname, "tinc.%s", netname);
269         else
270                 identname = xstrdup("tinc");
271
272 #ifdef HAVE_MINGW
273         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
274                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
275                         if(!confbase) {
276                                 if(netname)
277                                         xasprintf(&confbase, "%s/%s", installdir, netname);
278                                 else
279                                         xasprintf(&confbase, "%s", installdir);
280                         }
281                 }
282                 if(!controlcookiename)
283                         xasprintf(&controlcookiename, "%s/cookie", confbase);
284                 RegCloseKey(key);
285                 if(*installdir)
286                         return;
287         }
288 #endif
289
290         if(!controlcookiename)
291                 xasprintf(&controlcookiename, "%s/run/%s.cookie", LOCALSTATEDIR, identname);
292
293         if(netname) {
294                 if(!confbase)
295                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
296                 else
297                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
298         } else {
299                 if(!confbase)
300                         xasprintf(&confbase, CONFDIR "/tinc");
301         }
302 }
303
304 bool recvline(int fd, char *line, size_t len) {
305         static char buffer[4096];
306         static size_t blen = 0;
307         char *newline = NULL;
308
309         while(!(newline = memchr(buffer, '\n', blen))) {
310                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
311                 if(result == -1 && errno == EINTR)
312                         continue;
313                 else if(result <= 0)
314                         return false;
315                 blen += result;
316         }
317
318         if(newline - buffer >= len)
319                 return false;
320
321         len = newline - buffer;
322
323         memcpy(line, buffer, len);
324         line[len] = 0;
325         memmove(buffer, newline + 1, blen - len - 1);
326         blen -= len + 1;
327
328         return true;
329 }
330
331 bool sendline(int fd, char *format, ...) {
332         static char buffer[4096];
333         char *p = buffer;
334         size_t blen = 0;
335         va_list ap;
336
337         va_start(ap, format);
338         blen = vsnprintf(buffer, sizeof buffer, format, ap);
339         va_end(ap);
340
341         if(blen < 0 || blen >= sizeof buffer)
342                 return false;
343
344         buffer[blen] = '\n';
345         blen++;
346
347         while(blen) {
348                 int result = send(fd, p, blen, 0);
349                 if(result == -1 && errno == EINTR)
350                         continue;
351                 else if(result <= 0);
352                         return false;
353                 p += result;
354                 blen -= result;
355         }
356
357         return true;    
358 }
359
360 int main(int argc, char *argv[], char *envp[]) {
361         int fd;
362         int result;
363         int port;
364         int pid;
365
366         program_name = argv[0];
367
368         if(!parse_options(argc, argv))
369                 return 1;
370         
371         make_names();
372
373         if(show_version) {
374                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
375                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
376                 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
377                                 "See the AUTHORS file for a complete list.\n\n"
378                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
379                                 "and you are welcome to redistribute it under certain conditions;\n"
380                                 "see the file COPYING for details.\n");
381
382                 return 0;
383         }
384
385         if(show_help) {
386                 usage(false);
387                 return 0;
388         }
389
390         if(optind >= argc) {
391                 fprintf(stderr, "Not enough arguments.\n");
392                 usage(true);
393                 return 1;
394         }
395
396         // First handle commands that don't involve connecting to a running tinc daemon.
397
398         if(!strcasecmp(argv[optind], "generate-keys")) {
399                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
400         }
401
402         if(!strcasecmp(argv[optind], "start")) {
403                 argv[optind] = NULL;
404                 execve(SBINDIR "/tincd", argv, envp);
405                 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
406                 return 1;
407         }
408
409         /*
410          * Now handle commands that do involve connecting to a running tinc daemon.
411          * Authenticate the server by ensuring the parent directory can be
412          * traversed only by root. Note this is not totally race-free unless all
413          * ancestors are writable only by trusted users, which we don't verify.
414          */
415
416         FILE *f = fopen(controlcookiename, "r");
417         if(!f) {
418                 fprintf(stderr, "Could not open control socket cookie file %s: %s\n", controlcookiename, strerror(errno));
419                 return 1;
420         }
421         if(fscanf(f, "%1024s %d %d", controlcookie, &port, &pid) != 3) {
422                 fprintf(stderr, "Could not parse control socket cookie file %s\n", controlcookiename);
423                 return 1;
424         }
425
426 #ifdef HAVE_MINGW
427         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
428                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
429                 return 1;
430         }
431 #endif
432
433         struct sockaddr_in addr;
434         memset(&addr, 0, sizeof addr);
435         addr.sin_family = AF_INET;
436         addr.sin_addr.s_addr = htonl(0x7f000001);
437         addr.sin_port = htons(port);
438
439         fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
440         if(fd < 0) {
441                 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
442                 return 1;
443         }
444
445 #ifdef HAVE_MINGW
446         unsigned long arg = 0;
447
448         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
449                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
450         }
451 #endif
452
453         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
454                         
455                 fprintf(stderr, "Cannot connect to %s: %s\n", controlcookiename, sockstrerror(sockerrno));
456                 return 1;
457         }
458
459         char line[4096];
460         char data[4096];
461         int code, version, req;
462
463         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
464                 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
465                                 sockstrerror(sockerrno));
466                 return 1;
467         }
468
469         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
470         
471         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
472                 fprintf(stderr, "Could not fully establish control socket connection\n");
473                 return 1;
474         }
475
476         if(!strcasecmp(argv[optind], "pid")) {
477                 printf("%d\n", pid);
478                 return 0;
479         }
480
481         if(!strcasecmp(argv[optind], "stop")) {
482                 sendline(fd, "%d %d", CONTROL, REQ_STOP);
483                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
484                         fprintf(stderr, "Could not stop tinc daemon\n");
485                         return 1;
486                 }
487                 return 0;
488         }
489
490         if(!strcasecmp(argv[optind], "reload")) {
491                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
492                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
493                         fprintf(stderr, "Could not reload tinc daemon\n");
494                         return 1;
495                 }
496                 return 0;
497         }
498
499         if(!strcasecmp(argv[optind], "restart")) {
500                 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
501                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
502                         fprintf(stderr, "Could not restart tinc daemon\n");
503                         return 1;
504                 }
505                 return 0;
506         }
507
508         if(!strcasecmp(argv[optind], "retry")) {
509                 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
510                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
511                         fprintf(stderr, "Could not retry outgoing connections\n");
512                         return 1;
513                 }
514                 return 0;
515         }
516
517         if(!strcasecmp(argv[optind], "dump")) {
518                 if(argc < optind + 2) {
519                         fprintf(stderr, "Not enough arguments.\n");
520                         usage(true);
521                         return 1;
522                 }
523
524                 bool do_graph = false;
525                 int dumps = 1;
526
527                 if(!strcasecmp(argv[optind+1], "nodes"))
528                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
529                 else if(!strcasecmp(argv[optind+1], "edges"))
530                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
531                 else if(!strcasecmp(argv[optind+1], "subnets"))
532                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
533                 else if(!strcasecmp(argv[optind+1], "connections"))
534                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
535                 else if(!strcasecmp(argv[optind+1], "graph")) {
536                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
537                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
538                         do_graph = true;
539                         dumps = 2;
540                         printf("digraph {\n");
541                 } else {
542                         fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
543                         usage(true);
544                         return 1;
545                 }
546
547                 while(recvline(fd, line, sizeof line)) {
548                         char node1[4096], node2[4096];
549                         int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
550                         if(n == 2) {
551                                 if(do_graph && req == REQ_DUMP_NODES)
552                                         continue;
553                                 else {
554                                         if(do_graph)
555                                                 printf("}\n");
556                                         return 0;
557                                 }
558                         }
559                         if(n < 2)
560                                 break;
561
562                         if(!do_graph)
563                                 printf("%s\n", line + 5);
564                         else {
565                                 if(req == REQ_DUMP_NODES)
566                                         printf(" %s [label = \"%s\"];\n", node1, node1);
567                                 else
568                                         printf(" %s -> %s;\n", node1, node2);
569                         }
570                 }
571
572                 fprintf(stderr, "Error receiving dump\n");
573                 return 1;
574         }
575
576         if(!strcasecmp(argv[optind], "purge")) {
577                 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
578                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
579                         fprintf(stderr, "Could not purge tinc daemon\n");
580                         return 1;
581                 }
582                 return 0;
583         }
584
585         if(!strcasecmp(argv[optind], "debug")) {
586                 int debuglevel, origlevel;
587
588                 if(argc != optind + 2) {
589                         fprintf(stderr, "Invalid arguments.\n");
590                         return 1;
591                 }
592                 debuglevel = atoi(argv[optind+1]);
593
594                 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
595                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
596                         fprintf(stderr, "Could not purge tinc daemon\n");
597                         return 1;
598                 }
599
600                 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
601                 return 0;
602         }
603
604         if(!strcasecmp(argv[optind], "connect")) {
605                 if(argc != optind + 2) {
606                         fprintf(stderr, "Invalid arguments.\n");
607                         return 1;
608                 }
609                 char *name = argv[optind + 1];
610
611                 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
612                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
613                         fprintf(stderr, "Could not connect to %s\n", name);
614                         return 1;
615                 }
616                 return 0;
617         }
618
619         if(!strcasecmp(argv[optind], "disconnect")) {
620                 if(argc != optind + 2) {
621                         fprintf(stderr, "Invalid arguments.\n");
622                         return 1;
623                 }
624                 char *name = argv[optind + 1];
625
626                 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
627                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
628                         fprintf(stderr, "Could not disconnect %s\n", name);
629                         return 1;
630                 }
631                 return 0;
632         }
633
634 #ifdef HAVE_CURSES
635         if(!strcasecmp(argv[optind], "top")) {
636                 top(fd);
637                 return 0;
638         }
639 #endif
640
641         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
642         usage(true);
643         
644         close(fd);
645
646         return 0;
647 }