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