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