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