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