Allow log messages to be captured by tincctl.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2012 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 "ecdsagen.h"
28 #include "rsagen.h"
29 #include "utils.h"
30 #include "tincctl.h"
31 #include "top.h"
32
33 /* The name this program was run with. */
34 static char *program_name = NULL;
35
36 /* If nonzero, display usage information and exit. */
37 static bool show_help = false;
38
39 /* If nonzero, print the version on standard output and exit.  */
40 static bool show_version = false;
41
42 static char *name = NULL;
43 static char *identname = NULL;                          /* program name for syslog */
44 static char *pidfilename = NULL;                        /* pid file location */
45 static char controlcookie[1024];
46 char *netname = NULL;
47 char *confbase = NULL;
48
49 #ifdef HAVE_MINGW
50 static struct WSAData wsa_state;
51 #endif
52
53 static struct option const long_options[] = {
54         {"config", required_argument, NULL, 'c'},
55         {"net", required_argument, NULL, 'n'},
56         {"help", no_argument, NULL, 1},
57         {"version", no_argument, NULL, 2},
58         {"pidfile", required_argument, NULL, 5},
59         {NULL, 0, NULL, 0}
60 };
61
62 static void usage(bool status) {
63         if(status)
64                 fprintf(stderr, "Try `%s --help\' for more information.\n",
65                                 program_name);
66         else {
67                 printf("Usage: %s [options] command\n\n", program_name);
68                 printf("Valid options are:\n"
69                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
70                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
71                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
72                                 "      --help              Display this help and exit.\n"
73                                 "      --version           Output version information and exit.\n"
74                                 "\n"
75                                 "Valid commands are:\n"
76                                 "  start                      Start tincd.\n"
77                                 "  stop                       Stop tincd.\n"
78                                 "  restart                    Restart tincd.\n"
79                                 "  reload                     Partially reload configuration of running tincd.\n"
80                                 "  pid                        Show PID of currently running tincd.\n"
81                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
82                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
83                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
84                                 "  dump                       Dump a list of one of the following things:\n"
85                                 "    nodes                    - all known nodes in the VPN\n"
86                                 "    edges                    - all known connections in the VPN\n"
87                                 "    subnets                  - all known subnets in the VPN\n"
88                                 "    connections              - all meta connections with ourself\n"
89                                 "    graph                    - graph of the VPN in dotty format\n"
90                                 "  purge                      Purge unreachable nodes\n"
91                                 "  debug N                    Set debug level\n"
92                                 "  retry                      Retry all outgoing connections\n"
93                                 "  disconnect NODE            Close meta connection with NODE\n"
94 #ifdef HAVE_CURSES
95                                 "  top                        Show real-time statistics\n"
96 #endif
97                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
98                                 "  log [level]                Dump log output [up to the specified level]\n"
99                                 "\n");
100                 printf("Report bugs to tinc@tinc-vpn.org.\n");
101         }
102 }
103
104 static bool parse_options(int argc, char **argv) {
105         int r;
106         int option_index = 0;
107
108         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
109                 switch (r) {
110                         case 0:                         /* long option */
111                                 break;
112
113                         case 'c':                               /* config file */
114                                 confbase = xstrdup(optarg);
115                                 break;
116
117                         case 'n':                               /* net name given */
118                                 netname = xstrdup(optarg);
119                                 break;
120
121                         case 1:                                 /* show help */
122                                 show_help = true;
123                                 break;
124
125                         case 2:                                 /* show version */
126                                 show_version = true;
127                                 break;
128
129                         case 5:                                 /* open control socket here */
130                                 pidfilename = xstrdup(optarg);
131                                 break;
132
133                         case '?':
134                                 usage(true);
135                                 return false;
136
137                         default:
138                                 break;
139                 }
140         }
141
142         if(!netname) {
143                 netname = getenv("NETNAME");
144                 if(netname)
145                         netname = xstrdup(netname);
146         }
147
148         return true;
149 }
150
151 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
152         FILE *r;
153         char *directory;
154         char buf[PATH_MAX];
155         char buf2[PATH_MAX];
156
157         /* Check stdin and stdout */
158         if(isatty(0) && isatty(1)) {
159                 /* Ask for a file and/or directory name. */
160                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
161                                 what, filename);
162                 fflush(stdout);
163
164                 if(fgets(buf, sizeof buf, stdin) == NULL) {
165                         fprintf(stderr, "Error while reading stdin: %s\n",
166                                         strerror(errno));
167                         return NULL;
168                 }
169
170                 size_t len = strlen(buf);
171                 if(len)
172                         buf[--len] = 0;
173
174                 if(len)
175                         filename = buf;
176         }
177
178 #ifdef HAVE_MINGW
179         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
180 #else
181         if(filename[0] != '/') {
182 #endif
183                 /* The directory is a relative path or a filename. */
184                 directory = get_current_dir_name();
185                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
186                 filename = buf2;
187         }
188
189         umask(0077);                            /* Disallow everything for group and other */
190
191         /* Open it first to keep the inode busy */
192
193         r = fopen(filename, mode);
194
195         if(!r) {
196                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
197                 return NULL;
198         }
199
200         return r;
201 }
202
203 /*
204   Generate a public/private ECDSA keypair, and ask for a file to store
205   them in.
206 */
207 static bool ecdsa_keygen() {
208         ecdsa_t key;
209         FILE *f;
210         char *filename;
211
212         fprintf(stderr, "Generating ECDSA keypair:\n");
213
214         if(!ecdsa_generate(&key)) {
215                 fprintf(stderr, "Error during key generation!\n");
216                 return false;
217         } else
218                 fprintf(stderr, "Done.\n");
219
220         xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
221         f = ask_and_open(filename, "private ECDSA key", "a");
222
223         if(!f)
224                 return false;
225   
226 #ifdef HAVE_FCHMOD
227         /* Make it unreadable for others. */
228         fchmod(fileno(f), 0600);
229 #endif
230                 
231         if(ftell(f))
232                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
233
234         ecdsa_write_pem_private_key(&key, f);
235
236         fclose(f);
237         free(filename);
238
239         if(name)
240                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
241         else
242                 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
243
244         f = ask_and_open(filename, "public ECDSA key", "a");
245
246         if(!f)
247                 return false;
248
249         if(ftell(f))
250                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
251
252         char *pubkey = ecdsa_get_base64_public_key(&key);
253         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
254         free(pubkey);
255
256         fclose(f);
257         free(filename);
258
259         return true;
260 }
261
262 /*
263   Generate a public/private RSA keypair, and ask for a file to store
264   them in.
265 */
266 static bool rsa_keygen(int bits) {
267         rsa_t key;
268         FILE *f;
269         char *filename;
270
271         fprintf(stderr, "Generating %d bits keys:\n", bits);
272
273         if(!rsa_generate(&key, bits, 0x10001)) {
274                 fprintf(stderr, "Error during key generation!\n");
275                 return false;
276         } else
277                 fprintf(stderr, "Done.\n");
278
279         xasprintf(&filename, "%s/rsa_key.priv", confbase);
280         f = ask_and_open(filename, "private RSA key", "a");
281
282         if(!f)
283                 return false;
284   
285 #ifdef HAVE_FCHMOD
286         /* Make it unreadable for others. */
287         fchmod(fileno(f), 0600);
288 #endif
289                 
290         if(ftell(f))
291                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
292
293         rsa_write_pem_private_key(&key, f);
294
295         fclose(f);
296         free(filename);
297
298         if(name)
299                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
300         else
301                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
302
303         f = ask_and_open(filename, "public RSA key", "a");
304
305         if(!f)
306                 return false;
307
308         if(ftell(f))
309                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
310
311         rsa_write_pem_public_key(&key, f);
312
313         fclose(f);
314         free(filename);
315
316         return true;
317 }
318
319 /*
320   Set all files and paths according to netname
321 */
322 static void make_names(void) {
323 #ifdef HAVE_MINGW
324         HKEY key;
325         char installdir[1024] = "";
326         long len = sizeof installdir;
327 #endif
328
329         if(netname)
330                 xasprintf(&identname, "tinc.%s", netname);
331         else
332                 identname = xstrdup("tinc");
333
334 #ifdef HAVE_MINGW
335         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
336                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
337                         if(!confbase) {
338                                 if(netname)
339                                         xasprintf(&confbase, "%s/%s", installdir, netname);
340                                 else
341                                         xasprintf(&confbase, "%s", installdir);
342                         }
343                 }
344                 if(!pidfilename)
345                         xasprintf(&pidfilename, "%s/pid", confbase);
346                 RegCloseKey(key);
347                 if(*installdir)
348                         return;
349         }
350 #endif
351
352         if(!pidfilename)
353                 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
354
355         if(netname) {
356                 if(!confbase)
357                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
358                 else
359                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
360         } else {
361                 if(!confbase)
362                         xasprintf(&confbase, CONFDIR "/tinc");
363         }
364 }
365
366 static char buffer[4096];
367 static size_t blen = 0;
368
369 bool recvline(int fd, char *line, size_t len) {
370         char *newline = NULL;
371
372         while(!(newline = memchr(buffer, '\n', blen))) {
373                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
374                 if(result == -1 && errno == EINTR)
375                         continue;
376                 else if(result <= 0)
377                         return false;
378                 blen += result;
379         }
380
381         if(newline - buffer >= len)
382                 return false;
383
384         len = newline - buffer;
385
386         memcpy(line, buffer, len);
387         line[len] = 0;
388         memmove(buffer, newline + 1, blen - len - 1);
389         blen -= len + 1;
390
391         return true;
392 }
393
394 static bool recvdata(int fd, char *data, size_t len) {
395         while(blen < len) {
396                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
397                 if(result == -1 && errno == EINTR)
398                         continue;
399                 else if(result <= 0)
400                         return false;
401                 blen += result;
402         }
403
404         memcpy(data, buffer, len);
405         memmove(buffer, buffer + len, blen - len);
406         blen -= len;
407
408         return true;
409 }
410
411 bool sendline(int fd, char *format, ...) {
412         static char buffer[4096];
413         char *p = buffer;
414         int blen = 0;
415         va_list ap;
416
417         va_start(ap, format);
418         blen = vsnprintf(buffer, sizeof buffer, format, ap);
419         va_end(ap);
420
421         if(blen < 1 || blen >= sizeof buffer)
422                 return false;
423
424         buffer[blen] = '\n';
425         blen++;
426
427         while(blen) {
428                 int result = send(fd, p, blen, 0);
429                 if(result == -1 && errno == EINTR)
430                         continue;
431                 else if(result <= 0)
432                         return false;
433                 p += result;
434                 blen -= result;
435         }
436
437         return true;    
438 }
439
440 static void pcap(int fd, FILE *out, int snaplen) {
441         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
442         char data[9018];
443
444         struct {
445                 uint32_t magic;
446                 uint16_t major;
447                 uint16_t minor;
448                 uint32_t tz_offset;
449                 uint32_t tz_accuracy;
450                 uint32_t snaplen;
451                 uint32_t ll_type;
452         } header = {
453                 0xa1b2c3d4,
454                 2, 4,
455                 0, 0,
456                 snaplen ?: sizeof data,
457                 1,
458         };
459
460         struct {
461                 uint32_t tv_sec;
462                 uint32_t tv_usec;
463                 uint32_t len;
464                 uint32_t origlen;
465         } packet;
466
467         struct timeval tv;
468
469         fwrite(&header, sizeof header, 1, out);
470         fflush(out);
471
472         char line[32];
473         while(recvline(fd, line, sizeof line)) {
474                 int code, req, len;
475                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
476                 gettimeofday(&tv, NULL);
477                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
478                         break;
479                 if(!recvdata(fd, data, len))
480                         break;
481                 packet.tv_sec = tv.tv_sec;
482                 packet.tv_usec = tv.tv_usec;
483                 packet.len = len;
484                 packet.origlen = len;
485                 fwrite(&packet, sizeof packet, 1, out);
486                 fwrite(data, len, 1, out);
487                 fflush(out);
488         }
489 }
490
491 static void logcontrol(int fd, FILE *out, int level) {
492         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
493         char data[1024];
494         char line[32];
495
496         while(recvline(fd, line, sizeof line)) {
497                 int code, req, len;
498                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
499                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
500                         break;
501                 if(!recvdata(fd, data, len))
502                         break;
503                 fwrite(data, len, 1, out);
504                 fputc('\n', out);
505                 fflush(out);
506         }
507 }
508
509 #ifdef HAVE_MINGW
510 static bool remove_service(void) {
511         SC_HANDLE manager = NULL;
512         SC_HANDLE service = NULL;
513         SERVICE_STATUS status = {0};
514
515         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
516         if(!manager) {
517                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
518                 return false;
519         }
520
521         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
522
523         if(!service) {
524                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
525                 return false;
526         }
527
528         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
529                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
530         else
531                 fprintf(stderr, "%s service stopped\n", identname);
532
533         if(!DeleteService(service)) {
534                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
535                 return false;
536         }
537
538         fprintf(stderr, "%s service removed\n", identname);
539
540         return true;
541 }
542 #endif
543
544 int main(int argc, char *argv[]) {
545         int fd;
546         int result;
547         char host[128];
548         char port[128];
549         int pid;
550
551         program_name = argv[0];
552
553         if(!parse_options(argc, argv))
554                 return 1;
555         
556         make_names();
557
558         if(show_version) {
559                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
560                            VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
561                 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
562                                 "See the AUTHORS file for a complete list.\n\n"
563                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
564                                 "and you are welcome to redistribute it under certain conditions;\n"
565                                 "see the file COPYING for details.\n");
566
567                 return 0;
568         }
569
570         if(show_help) {
571                 usage(false);
572                 return 0;
573         }
574
575         if(optind >= argc) {
576                 fprintf(stderr, "Not enough arguments.\n");
577                 usage(true);
578                 return 1;
579         }
580
581         // First handle commands that don't involve connecting to a running tinc daemon.
582
583         if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
584                 return !rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048);
585         }
586
587         if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
588                 return !ecdsa_keygen();
589         }
590
591         if(!strcasecmp(argv[optind], "generate-keys")) {
592                 return !(rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
593         }
594
595         if(!strcasecmp(argv[optind], "start")) {
596                 int i, j;
597                 char *c;
598                 char *slash = strrchr(argv[0], '/');
599 #ifdef HAVE_MINGW
600                 if ((c = strrchr(argv[0], '\\')) > slash)
601                         slash = c;
602 #endif
603                 if (slash++) {
604                         c = xmalloc((slash - argv[0]) + sizeof("tincd"));
605                         sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
606                 }
607                 else
608                         c = "tincd";
609                 argv[0] = c;
610                 for(i = j = 1; argv[i]; ++i)
611                         if (i != optind && strcmp(argv[i], "--") != 0)
612                                 argv[j++] = argv[i];
613                 argv[j] = NULL;
614                 execvp(c, argv);
615                 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
616                 return 1;
617         }
618
619         /*
620          * Now handle commands that do involve connecting to a running tinc daemon.
621          * Authenticate the server by ensuring the parent directory can be
622          * traversed only by root. Note this is not totally race-free unless all
623          * ancestors are writable only by trusted users, which we don't verify.
624          */
625
626         FILE *f = fopen(pidfilename, "r");
627         if(!f) {
628                 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
629                 return 1;
630         }
631         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
632                 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
633                 return 1;
634         }
635
636 #ifdef HAVE_MINGW
637         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
638                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
639                 return 1;
640         }
641 #endif
642
643         struct addrinfo hints = {
644                 .ai_family = AF_UNSPEC,
645                 .ai_socktype = SOCK_STREAM,
646                 .ai_protocol = IPPROTO_TCP,
647                 .ai_flags = 0,
648         };
649
650         struct addrinfo *res = NULL;
651
652         if(getaddrinfo(host, port, &hints, &res) || !res) {
653                 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
654                 return 1;
655         }
656
657         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
658         if(fd < 0) {
659                 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
660                 return 1;
661         }
662
663 #ifdef HAVE_MINGW
664         unsigned long arg = 0;
665
666         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
667                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
668         }
669 #endif
670
671         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
672                 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
673                 return 1;
674         }
675
676         freeaddrinfo(res);
677
678         char line[4096];
679         char data[4096];
680         int code, version, req;
681
682         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
683                 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
684                                 sockstrerror(sockerrno));
685                 return 1;
686         }
687
688         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
689         
690         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
691                 fprintf(stderr, "Could not fully establish control socket connection\n");
692                 return 1;
693         }
694
695         if(!strcasecmp(argv[optind], "pid")) {
696                 printf("%d\n", pid);
697                 return 0;
698         }
699
700         if(!strcasecmp(argv[optind], "stop")) {
701 #ifndef HAVE_MINGW
702                 sendline(fd, "%d %d", CONTROL, REQ_STOP);
703                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
704                         fprintf(stderr, "Could not stop tinc daemon\n");
705                         return 1;
706                 }
707 #else
708                 if(!remove_service())
709                         return 1;
710 #endif
711                 return 0;
712         }
713
714         if(!strcasecmp(argv[optind], "reload")) {
715                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
716                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
717                         fprintf(stderr, "Could not reload tinc daemon\n");
718                         return 1;
719                 }
720                 return 0;
721         }
722
723         if(!strcasecmp(argv[optind], "restart")) {
724                 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
725                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
726                         fprintf(stderr, "Could not restart tinc daemon\n");
727                         return 1;
728                 }
729                 return 0;
730         }
731
732         if(!strcasecmp(argv[optind], "retry")) {
733                 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
734                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
735                         fprintf(stderr, "Could not retry outgoing connections\n");
736                         return 1;
737                 }
738                 return 0;
739         }
740
741         if(!strcasecmp(argv[optind], "dump")) {
742                 if(argc < optind + 2) {
743                         fprintf(stderr, "Not enough arguments.\n");
744                         usage(true);
745                         return 1;
746                 }
747
748                 bool do_graph = false;
749
750                 if(!strcasecmp(argv[optind+1], "nodes"))
751                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
752                 else if(!strcasecmp(argv[optind+1], "edges"))
753                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
754                 else if(!strcasecmp(argv[optind+1], "subnets"))
755                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
756                 else if(!strcasecmp(argv[optind+1], "connections"))
757                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
758                 else if(!strcasecmp(argv[optind+1], "graph")) {
759                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
760                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
761                         do_graph = true;
762                         printf("digraph {\n");
763                 } else {
764                         fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
765                         usage(true);
766                         return 1;
767                 }
768
769                 while(recvline(fd, line, sizeof line)) {
770                         char node1[4096], node2[4096];
771                         int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
772                         if(n == 2) {
773                                 if(do_graph && req == REQ_DUMP_NODES)
774                                         continue;
775                                 else {
776                                         if(do_graph)
777                                                 printf("}\n");
778                                         return 0;
779                                 }
780                         }
781                         if(n < 2)
782                                 break;
783
784                         if(!do_graph)
785                                 printf("%s\n", line + 5);
786                         else {
787                                 if(req == REQ_DUMP_NODES)
788                                         printf(" %s [label = \"%s\"];\n", node1, node1);
789                                 else
790                                         printf(" %s -> %s;\n", node1, node2);
791                         }
792                 }
793
794                 fprintf(stderr, "Error receiving dump\n");
795                 return 1;
796         }
797
798         if(!strcasecmp(argv[optind], "purge")) {
799                 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
800                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
801                         fprintf(stderr, "Could not purge tinc daemon\n");
802                         return 1;
803                 }
804                 return 0;
805         }
806
807         if(!strcasecmp(argv[optind], "debug")) {
808                 int debuglevel, origlevel;
809
810                 if(argc != optind + 2) {
811                         fprintf(stderr, "Invalid arguments.\n");
812                         return 1;
813                 }
814                 debuglevel = atoi(argv[optind+1]);
815
816                 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
817                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
818                         fprintf(stderr, "Could not purge tinc daemon\n");
819                         return 1;
820                 }
821
822                 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
823                 return 0;
824         }
825
826         if(!strcasecmp(argv[optind], "connect")) {
827                 if(argc != optind + 2) {
828                         fprintf(stderr, "Invalid arguments.\n");
829                         return 1;
830                 }
831                 char *name = argv[optind + 1];
832
833                 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
834                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
835                         fprintf(stderr, "Could not connect to %s\n", name);
836                         return 1;
837                 }
838                 return 0;
839         }
840
841         if(!strcasecmp(argv[optind], "disconnect")) {
842                 if(argc != optind + 2) {
843                         fprintf(stderr, "Invalid arguments.\n");
844                         return 1;
845                 }
846                 char *name = argv[optind + 1];
847
848                 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
849                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
850                         fprintf(stderr, "Could not disconnect %s\n", name);
851                         return 1;
852                 }
853                 return 0;
854         }
855
856 #ifdef HAVE_CURSES
857         if(!strcasecmp(argv[optind], "top")) {
858                 top(fd);
859                 return 0;
860         }
861 #endif
862
863         if(!strcasecmp(argv[optind], "pcap")) {
864                 pcap(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : 0);
865                 return 0;
866         }
867
868         if(!strcasecmp(argv[optind], "log")) {
869                 logcontrol(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : -1);
870                 return 0;
871         }
872
873         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
874         usage(true);
875         
876         close(fd);
877
878         return 0;
879 }