Add an easy way to export and import host configuration files.
[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 "info.h"
29 #include "rsagen.h"
30 #include "utils.h"
31 #include "tincctl.h"
32 #include "top.h"
33
34 /* The name this program was run with. */
35 static char *program_name = NULL;
36
37 /* If nonzero, display usage information and exit. */
38 static bool show_help = false;
39
40 /* If nonzero, print the version on standard output and exit.  */
41 static bool show_version = false;
42
43 static char *name = NULL;
44 static char *identname = NULL;                          /* program name for syslog */
45 static char *pidfilename = NULL;                        /* pid file location */
46 static char controlcookie[1024];
47 char *netname = NULL;
48 char *confbase = NULL;
49 static char *tinc_conf = NULL;
50 static char *hosts_dir = NULL;
51
52 // Horrible global variables...
53 static int pid = 0;
54 static int fd = -1;
55 static char line[4096];
56 static int code;
57 static int req;
58 static int result;
59 static bool force = false;
60
61 #ifdef HAVE_MINGW
62 static struct WSAData wsa_state;
63 #endif
64
65 static struct option const long_options[] = {
66         {"config", required_argument, NULL, 'c'},
67         {"debug", optional_argument, NULL, 0},
68         {"no-detach", no_argument, NULL, 0},
69         {"mlock", no_argument, NULL, 0},
70         {"net", required_argument, NULL, 'n'},
71         {"help", no_argument, NULL, 1},
72         {"version", no_argument, NULL, 2},
73         {"pidfile", required_argument, NULL, 5},
74         {"logfile", required_argument, NULL, 0},
75         {"bypass-security", no_argument, NULL, 0},
76         {"chroot", no_argument, NULL, 0},
77         {"user", required_argument, NULL, 0},
78         {"option", required_argument, NULL, 0},
79         {"force", no_argument, NULL, 6},
80         {NULL, 0, NULL, 0}
81 };
82
83 static void version(void) {
84         printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
85                    VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
86         printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
87                         "See the AUTHORS file for a complete list.\n\n"
88                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
89                         "and you are welcome to redistribute it under certain conditions;\n"
90                         "see the file COPYING for details.\n");
91 }
92
93 static void usage(bool status) {
94         if(status)
95                 fprintf(stderr, "Try `%s --help\' for more information.\n",
96                                 program_name);
97         else {
98                 printf("Usage: %s [options] command\n\n", program_name);
99                 printf("Valid options are:\n"
100                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
101                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
102                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
103                                 "      --help              Display this help and exit.\n"
104                                 "      --version           Output version information and exit.\n"
105                                 "\n"
106                                 "Valid commands are:\n"
107                                 "  init [name]                Create initial configuration files.\n"
108                                 "  config                     Change configuration:\n"
109                                 "    [set] VARIABLE VALUE     - set VARIABLE to VALUE\n"
110                                 "    add VARIABLE VALUE       - add VARIABLE with the given VALUE\n"
111                                 "    del VARIABLE [VALUE]     - remove VARIABLE [only ones with watching VALUE]\n"
112                                 "  start [tincd options]      Start tincd.\n"
113                                 "  stop                       Stop tincd.\n"
114                                 "  restart                    Restart tincd.\n"
115                                 "  reload                     Partially reload configuration of running tincd.\n"
116                                 "  pid                        Show PID of currently running tincd.\n"
117                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
118                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
119                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
120                                 "  dump                       Dump a list of one of the following things:\n"
121                                 "    nodes                    - all known nodes in the VPN\n"
122                                 "    edges                    - all known connections in the VPN\n"
123                                 "    subnets                  - all known subnets in the VPN\n"
124                                 "    connections              - all meta connections with ourself\n"
125                                 "    graph                    - graph of the VPN in dotty format\n"
126                                 "  info NODE|SUBNET|ADDRESS   Give information about a particular NODE, SUBNET or ADDRESS.\n"
127                                 "  purge                      Purge unreachable nodes\n"
128                                 "  debug N                    Set debug level\n"
129                                 "  retry                      Retry all outgoing connections\n"
130                                 "  disconnect NODE            Close meta connection with NODE\n"
131 #ifdef HAVE_CURSES
132                                 "  top                        Show real-time statistics\n"
133 #endif
134                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
135                                 "  log [level]                Dump log output [up to the specified level]\n"
136                                 "  export                     Export host configuration of local node to standard output\n"
137                                 "  export-all                 Export all host configuration files to standard output\n"
138                                 "  import [--force]           Import host configuration file(s) from standard input\n"
139                                 "\n");
140                 printf("Report bugs to tinc@tinc-vpn.org.\n");
141         }
142 }
143
144 static bool parse_options(int argc, char **argv) {
145         int r;
146         int option_index = 0;
147
148         while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
149                 switch (r) {
150                         case 0:                         /* long option */
151                                 break;
152
153                         case 'c':                               /* config file */
154                                 confbase = xstrdup(optarg);
155                                 break;
156
157                         case 'n':                               /* net name given */
158                                 netname = xstrdup(optarg);
159                                 break;
160
161                         case 1:                                 /* show help */
162                                 show_help = true;
163                                 break;
164
165                         case 2:                                 /* show version */
166                                 show_version = true;
167                                 break;
168
169                         case 5:                                 /* open control socket here */
170                                 pidfilename = xstrdup(optarg);
171                                 break;
172
173                         case 6:
174                                 force = true;
175                                 break;
176
177                         case '?':
178                                 usage(true);
179                                 return false;
180
181                         default:
182                                 break;
183                 }
184         }
185
186         if(!netname) {
187                 netname = getenv("NETNAME");
188                 if(netname)
189                         netname = xstrdup(netname);
190         }
191
192         return true;
193 }
194
195 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
196         FILE *r;
197         char *directory;
198         char buf[PATH_MAX];
199         char buf2[PATH_MAX];
200
201         /* Check stdin and stdout */
202         if(isatty(0) && isatty(1)) {
203                 /* Ask for a file and/or directory name. */
204                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
205                                 what, filename);
206                 fflush(stdout);
207
208                 if(fgets(buf, sizeof buf, stdin) == NULL) {
209                         fprintf(stderr, "Error while reading stdin: %s\n",
210                                         strerror(errno));
211                         return NULL;
212                 }
213
214                 size_t len = strlen(buf);
215                 if(len)
216                         buf[--len] = 0;
217
218                 if(len)
219                         filename = buf;
220         }
221
222 #ifdef HAVE_MINGW
223         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
224 #else
225         if(filename[0] != '/') {
226 #endif
227                 /* The directory is a relative path or a filename. */
228                 directory = get_current_dir_name();
229                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
230                 filename = buf2;
231         }
232
233         umask(0077);                            /* Disallow everything for group and other */
234
235         /* Open it first to keep the inode busy */
236
237         r = fopen(filename, mode);
238
239         if(!r) {
240                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
241                 return NULL;
242         }
243
244         return r;
245 }
246
247 /*
248   Generate a public/private ECDSA keypair, and ask for a file to store
249   them in.
250 */
251 static bool ecdsa_keygen() {
252         ecdsa_t key;
253         FILE *f;
254         char *filename;
255
256         fprintf(stderr, "Generating ECDSA keypair:\n");
257
258         if(!ecdsa_generate(&key)) {
259                 fprintf(stderr, "Error during key generation!\n");
260                 return false;
261         } else
262                 fprintf(stderr, "Done.\n");
263
264         xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
265         f = ask_and_open(filename, "private ECDSA key", "a");
266
267         if(!f)
268                 return false;
269   
270 #ifdef HAVE_FCHMOD
271         /* Make it unreadable for others. */
272         fchmod(fileno(f), 0600);
273 #endif
274                 
275         if(ftell(f))
276                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
277
278         ecdsa_write_pem_private_key(&key, f);
279
280         fclose(f);
281         free(filename);
282
283         if(name)
284                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
285         else
286                 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
287
288         f = ask_and_open(filename, "public ECDSA key", "a");
289
290         if(!f)
291                 return false;
292
293         if(ftell(f))
294                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
295
296         char *pubkey = ecdsa_get_base64_public_key(&key);
297         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
298         free(pubkey);
299
300         fclose(f);
301         free(filename);
302
303         return true;
304 }
305
306 /*
307   Generate a public/private RSA keypair, and ask for a file to store
308   them in.
309 */
310 static bool rsa_keygen(int bits) {
311         rsa_t key;
312         FILE *f;
313         char *filename;
314
315         fprintf(stderr, "Generating %d bits keys:\n", bits);
316
317         if(!rsa_generate(&key, bits, 0x10001)) {
318                 fprintf(stderr, "Error during key generation!\n");
319                 return false;
320         } else
321                 fprintf(stderr, "Done.\n");
322
323         xasprintf(&filename, "%s/rsa_key.priv", confbase);
324         f = ask_and_open(filename, "private RSA key", "a");
325
326         if(!f)
327                 return false;
328   
329 #ifdef HAVE_FCHMOD
330         /* Make it unreadable for others. */
331         fchmod(fileno(f), 0600);
332 #endif
333                 
334         if(ftell(f))
335                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
336
337         rsa_write_pem_private_key(&key, f);
338
339         fclose(f);
340         free(filename);
341
342         if(name)
343                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
344         else
345                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
346
347         f = ask_and_open(filename, "public RSA key", "a");
348
349         if(!f)
350                 return false;
351
352         if(ftell(f))
353                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
354
355         rsa_write_pem_public_key(&key, f);
356
357         fclose(f);
358         free(filename);
359
360         return true;
361 }
362
363 /*
364   Set all files and paths according to netname
365 */
366 static void make_names(void) {
367 #ifdef HAVE_MINGW
368         HKEY key;
369         char installdir[1024] = "";
370         long len = sizeof installdir;
371 #endif
372
373         if(netname)
374                 xasprintf(&identname, "tinc.%s", netname);
375         else
376                 identname = xstrdup("tinc");
377
378 #ifdef HAVE_MINGW
379         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
380                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
381                         if(!confbase) {
382                                 if(netname)
383                                         xasprintf(&confbase, "%s/%s", installdir, netname);
384                                 else
385                                         xasprintf(&confbase, "%s", installdir);
386                         }
387                 }
388                 if(!pidfilename)
389                         xasprintf(&pidfilename, "%s/pid", confbase);
390                 RegCloseKey(key);
391         }
392
393         if(!*installdir) {
394 #endif
395
396         if(!pidfilename)
397                 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
398
399         if(netname) {
400                 if(!confbase)
401                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
402                 else
403                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
404         } else {
405                 if(!confbase)
406                         xasprintf(&confbase, CONFDIR "/tinc");
407         }
408
409 #ifdef HAVE_MINGW
410         }
411 #endif
412
413         xasprintf(&tinc_conf, "%s/tinc.conf", confbase);
414         xasprintf(&hosts_dir, "%s/hosts", confbase);
415 }
416
417 static char buffer[4096];
418 static size_t blen = 0;
419
420 bool recvline(int fd, char *line, size_t len) {
421         char *newline = NULL;
422
423         while(!(newline = memchr(buffer, '\n', blen))) {
424                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
425                 if(result == -1 && errno == EINTR)
426                         continue;
427                 else if(result <= 0)
428                         return false;
429                 blen += result;
430         }
431
432         if(newline - buffer >= len)
433                 return false;
434
435         len = newline - buffer;
436
437         memcpy(line, buffer, len);
438         line[len] = 0;
439         memmove(buffer, newline + 1, blen - len - 1);
440         blen -= len + 1;
441
442         return true;
443 }
444
445 static bool recvdata(int fd, char *data, size_t len) {
446         while(blen < len) {
447                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
448                 if(result == -1 && errno == EINTR)
449                         continue;
450                 else if(result <= 0)
451                         return false;
452                 blen += result;
453         }
454
455         memcpy(data, buffer, len);
456         memmove(buffer, buffer + len, blen - len);
457         blen -= len;
458
459         return true;
460 }
461
462 bool sendline(int fd, char *format, ...) {
463         static char buffer[4096];
464         char *p = buffer;
465         int blen = 0;
466         va_list ap;
467
468         va_start(ap, format);
469         blen = vsnprintf(buffer, sizeof buffer, format, ap);
470         va_end(ap);
471
472         if(blen < 1 || blen >= sizeof buffer)
473                 return false;
474
475         buffer[blen] = '\n';
476         blen++;
477
478         while(blen) {
479                 int result = send(fd, p, blen, 0);
480                 if(result == -1 && errno == EINTR)
481                         continue;
482                 else if(result <= 0)
483                         return false;
484                 p += result;
485                 blen -= result;
486         }
487
488         return true;    
489 }
490
491 static void pcap(int fd, FILE *out, int snaplen) {
492         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
493         char data[9018];
494
495         struct {
496                 uint32_t magic;
497                 uint16_t major;
498                 uint16_t minor;
499                 uint32_t tz_offset;
500                 uint32_t tz_accuracy;
501                 uint32_t snaplen;
502                 uint32_t ll_type;
503         } header = {
504                 0xa1b2c3d4,
505                 2, 4,
506                 0, 0,
507                 snaplen ?: sizeof data,
508                 1,
509         };
510
511         struct {
512                 uint32_t tv_sec;
513                 uint32_t tv_usec;
514                 uint32_t len;
515                 uint32_t origlen;
516         } packet;
517
518         struct timeval tv;
519
520         fwrite(&header, sizeof header, 1, out);
521         fflush(out);
522
523         char line[32];
524         while(recvline(fd, line, sizeof line)) {
525                 int code, req, len;
526                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
527                 gettimeofday(&tv, NULL);
528                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
529                         break;
530                 if(!recvdata(fd, data, len))
531                         break;
532                 packet.tv_sec = tv.tv_sec;
533                 packet.tv_usec = tv.tv_usec;
534                 packet.len = len;
535                 packet.origlen = len;
536                 fwrite(&packet, sizeof packet, 1, out);
537                 fwrite(data, len, 1, out);
538                 fflush(out);
539         }
540 }
541
542 static void logcontrol(int fd, FILE *out, int level) {
543         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
544         char data[1024];
545         char line[32];
546
547         while(recvline(fd, line, sizeof line)) {
548                 int code, req, len;
549                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
550                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
551                         break;
552                 if(!recvdata(fd, data, len))
553                         break;
554                 fwrite(data, len, 1, out);
555                 fputc('\n', out);
556                 fflush(out);
557         }
558 }
559
560 #ifdef HAVE_MINGW
561 static bool remove_service(void) {
562         SC_HANDLE manager = NULL;
563         SC_HANDLE service = NULL;
564         SERVICE_STATUS status = {0};
565
566         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
567         if(!manager) {
568                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
569                 return false;
570         }
571
572         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
573
574         if(!service) {
575                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
576                 return false;
577         }
578
579         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
580                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
581         else
582                 fprintf(stderr, "%s service stopped\n", identname);
583
584         if(!DeleteService(service)) {
585                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
586                 return false;
587         }
588
589         fprintf(stderr, "%s service removed\n", identname);
590
591         return true;
592 }
593 #endif
594
595 static bool connect_tincd() {
596         if(fd >= 0)
597                 return true;
598
599         FILE *f = fopen(pidfilename, "r");
600         if(!f) {
601                 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
602                 return false;
603         }
604
605         char host[128];
606         char port[128];
607
608         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
609                 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
610                 return false;
611         }
612
613 #ifdef HAVE_MINGW
614         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
615                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
616                 return false;
617         }
618 #endif
619
620         struct addrinfo hints = {
621                 .ai_family = AF_UNSPEC,
622                 .ai_socktype = SOCK_STREAM,
623                 .ai_protocol = IPPROTO_TCP,
624                 .ai_flags = 0,
625         };
626
627         struct addrinfo *res = NULL;
628
629         if(getaddrinfo(host, port, &hints, &res) || !res) {
630                 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
631                 return false;
632         }
633
634         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
635         if(fd < 0) {
636                 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
637                 return false;
638         }
639
640 #ifdef HAVE_MINGW
641         unsigned long arg = 0;
642
643         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
644                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
645         }
646 #endif
647
648         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
649                 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
650                 return false;
651         }
652
653         freeaddrinfo(res);
654
655         char data[4096];
656         int version;
657
658         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
659                 fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
660                 return false;
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 false;
668         }
669
670         return true;
671 }
672
673
674 static int cmd_start(int argc, char *argv[]) {
675         int i, j;
676         char *c;
677
678         argc += optind;
679         argv -= optind;
680         char *slash = strrchr(argv[0], '/');
681
682 #ifdef HAVE_MINGW
683         if ((c = strrchr(argv[0], '\\')) > slash)
684                 slash = c;
685 #endif
686
687         if (slash++) {
688                 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
689                 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
690         }
691         else
692                 c = "tincd";
693
694         argv[0] = c;
695
696         for(i = j = 1; argv[i]; ++i)
697                 if (i != optind && strcmp(argv[i], "--") != 0)
698                         argv[j++] = argv[i];
699
700         argv[j] = NULL;
701         execvp(c, argv);
702         fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
703         return 1;
704 }
705
706 static int cmd_stop(int argc, char *argv[]) {
707 #ifndef HAVE_MINGW
708         if(!connect_tincd())
709                 return 1;
710
711         sendline(fd, "%d %d", CONTROL, REQ_STOP);
712         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
713                 fprintf(stderr, "Could not stop tinc daemon.\n");
714                 return 1;
715         }
716 #else
717         if(!remove_service())
718                 return 1;
719 #endif
720         return 0;
721 }
722
723 static int cmd_restart(int argc, char *argv[]) {
724         return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
725 }
726
727 static int cmd_reload(int argc, char *argv[]) {
728         if(!connect_tincd())
729                 return 1;
730
731         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
732         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
733                 fprintf(stderr, "Could not reload configuration.\n");
734                 return 1;
735         }
736
737         return 0;
738
739 }
740
741 static int cmd_dump(int argc, char *argv[]) {
742         if(argc != 2) {
743                 fprintf(stderr, "Invalid number of arguments.\n");
744                 usage(true);
745                 return 1;
746         }
747
748         if(!connect_tincd())
749                 return 1;
750
751         bool do_graph = false;
752
753         if(!strcasecmp(argv[1], "nodes"))
754                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
755         else if(!strcasecmp(argv[1], "edges"))
756                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
757         else if(!strcasecmp(argv[1], "subnets"))
758                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
759         else if(!strcasecmp(argv[1], "connections"))
760                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
761         else if(!strcasecmp(argv[1], "graph")) {
762                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
763                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
764                 do_graph = true;
765         } else {
766                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
767                 usage(true);
768                 return 1;
769         }
770
771         if(do_graph)
772                 printf("digraph {\n");
773
774         while(recvline(fd, line, sizeof line)) {
775                 char node1[4096], node2[4096];
776                 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
777                 if(n == 2) {
778                         if(do_graph && req == REQ_DUMP_NODES)
779                                 continue;
780                         else {
781                                 if(do_graph)
782                                         printf("}\n");
783                                 return 0;
784                         }
785                 }
786                 if(n < 2)
787                         break;
788
789                 if(!do_graph)
790                         printf("%s\n", line + 5);
791                 else {
792                         if(req == REQ_DUMP_NODES)
793                                 printf(" %s [label = \"%s\"];\n", node1, node1);
794                         else
795                                 printf(" %s -> %s;\n", node1, node2);
796                 }
797         }
798
799         fprintf(stderr, "Error receiving dump.\n");
800         return 1;
801 }
802
803 static int cmd_purge(int argc, char *argv[]) {
804         if(!connect_tincd())
805                 return 1;
806
807         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
808         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
809                 fprintf(stderr, "Could not purge old information.\n");
810                 return 1;
811         }
812
813         return 0;
814 }
815
816 static int cmd_debug(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         int debuglevel = atoi(argv[1]);
826         int origlevel;
827
828         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
829         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
830                 fprintf(stderr, "Could not set debug level.\n");
831                 return 1;
832         }
833
834         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
835         return 0;
836 }
837
838 static int cmd_retry(int argc, char *argv[]) {
839         if(!connect_tincd())
840                 return 1;
841
842         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
843         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
844                 fprintf(stderr, "Could not retry outgoing connections.\n");
845                 return 1;
846         }
847
848         return 0;
849 }
850
851 static int cmd_connect(int argc, char *argv[]) {
852         if(argc != 2) {
853                 fprintf(stderr, "Invalid number of arguments.\n");
854                 return 1;
855         }
856
857         if(!check_id(argv[2])) {
858                 fprintf(stderr, "Invalid name for node.\n");
859                 return 1;
860         }
861
862         if(!connect_tincd())
863                 return 1;
864
865         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
866         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
867                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
868                 return 1;
869         }
870
871         return 0;
872 }
873
874 static int cmd_disconnect(int argc, char *argv[]) {
875         if(argc != 2) {
876                 fprintf(stderr, "Invalid number of arguments.\n");
877                 return 1;
878         }
879
880         if(!check_id(argv[2])) {
881                 fprintf(stderr, "Invalid name for node.\n");
882                 return 1;
883         }
884
885         if(!connect_tincd())
886                 return 1;
887
888         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
889         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
890                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
891                 return 1;
892         }
893
894         return 0;
895 }
896
897 static int cmd_top(int argc, char *argv[]) {
898 #ifdef HAVE_CURSES
899         if(!connect_tincd())
900                 return 1;
901
902         top(fd);
903         return 0;
904 #else
905         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
906         return 1;
907 #endif
908 }
909
910 static int cmd_pcap(int argc, char *argv[]) {
911         if(!connect_tincd())
912                 return 1;
913
914         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
915         return 0;
916 }
917
918 static int cmd_log(int argc, char *argv[]) {
919         if(!connect_tincd())
920                 return 1;
921
922         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
923         return 0;
924 }
925
926 static int cmd_pid(int argc, char *argv[]) {
927         if(!connect_tincd())
928                 return 1;
929
930         printf("%d\n", pid);
931         return 0;
932 }
933
934 static int rstrip(char *value) {
935         int len = strlen(value);
936         while(len && strchr("\t\r\n ", value[len - 1]))
937                 value[--len] = 0;
938         return len;
939 }
940
941 static char *get_my_name() {
942         FILE *f = fopen(tinc_conf, "r");
943         if(!f) {
944                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
945                 return NULL;
946         }
947
948         char buf[4096];
949         char *value;
950         while(fgets(buf, sizeof buf, f)) {
951                 int len = strcspn(buf, "\t =");
952                 value = buf + len;
953                 value += strspn(value, "\t ");
954                 if(*value == '=') {
955                         value++;
956                         value += strspn(value, "\t ");
957                 }
958                 if(!rstrip(value))
959                         continue;
960                 buf[len] = 0;
961                 if(strcasecmp(buf, "Name"))
962                         continue;
963                 if(*value) {
964                         fclose(f);
965                         return strdup(value);
966                 }
967         }
968
969         fclose(f);
970         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
971         return NULL;
972 }
973
974 static char *hostvariables[] = {
975         "Address",
976         "Port",
977         "PublicKey",
978         "Subnet",
979         NULL,
980 };
981
982 static int cmd_config(int argc, char *argv[]) {
983         if(argc < 2) {
984                 fprintf(stderr, "Invalid number of arguments.\n");
985                 return 1;
986         }
987
988         int action = 0;
989         if(!strcasecmp(argv[1], "add")) {
990                 argv++, argc--, action = 1;
991         } else if(!strcasecmp(argv[1], "del")) {
992                 argv++, argc--, action = -1;
993         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
994                 argv++, argc--, action = 0;
995         }
996
997         if(argc < 2) {
998                 fprintf(stderr, "Invalid number of arguments.\n");
999                 return 1;
1000         }
1001
1002         // Concatenate the rest of the command line
1003         strncpy(line, argv[1], sizeof line - 1);
1004         for(int i = 2; i < argc; i++) {
1005                 strncat(line, " ", sizeof line - 1 - strlen(line));
1006                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1007         }
1008
1009         // Liberal parsing into node name, variable name and value.
1010         char *node = NULL;
1011         char *variable;
1012         char *value;
1013         int len;
1014
1015         len = strcspn(line, "\t =");
1016         value = line + len;
1017         value += strspn(value, "\t ");
1018         if(*value == '=') {
1019                 value++;
1020                 value += strspn(value, "\t ");
1021         }
1022         line[len] = '\0';
1023         variable = strchr(line, '.');
1024         if(variable) {
1025                 node = line;
1026                 *variable++ = 0;
1027         } else {
1028                 variable = line;
1029         }
1030
1031         if(!*variable) {
1032                 fprintf(stderr, "No variable given.\n");
1033                 return 1;
1034         }
1035
1036         if(action >= 0 && !*value) {
1037                 fprintf(stderr, "No value for variable given.\n");
1038                 return 1;
1039         }
1040
1041         // Should this go into our own host config file?
1042         if(!node) {
1043                 for(int i = 0; hostvariables[i]; i++) {
1044                         if(!strcasecmp(hostvariables[i], variable)) {
1045                                 node = get_my_name();
1046                                 if(!node)
1047                                         return 1;
1048                                 break;
1049                         }
1050                 }
1051         }
1052
1053         if(node && !check_id(node)) {
1054                 fprintf(stderr, "Invalid name for node.\n");
1055                 return 1;
1056         }
1057
1058         // Open the right configuration file.
1059         char *filename;
1060         if(node)
1061                 xasprintf(&filename, "%s/%s", hosts_dir, node);
1062         else
1063                 filename = tinc_conf;
1064
1065         FILE *f = fopen(filename, "r");
1066         if(!f) {
1067                 if(action < 0 || errno != ENOENT) {
1068                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1069                         return 1;
1070                 }
1071
1072                 // If it doesn't exist, create it.
1073                 f = fopen(filename, "a+");
1074                 if(!f) {
1075                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1076                         return 1;
1077                 } else {
1078                         fprintf(stderr, "Created configuration file %s.\n", filename);
1079                 }
1080         }
1081
1082         char *tmpfile;
1083         xasprintf(&tmpfile, "%s.config.tmp", filename);
1084         FILE *tf = fopen(tmpfile, "w");
1085         if(!tf) {
1086                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1087                 return 1;
1088         }
1089
1090         // Copy the file, making modifications on the fly.
1091         char buf1[4096];
1092         char buf2[4096];
1093         bool set = false;
1094         bool removed = false;
1095
1096         while(fgets(buf1, sizeof buf1, f)) {
1097                 buf1[sizeof buf1 - 1] = 0;
1098                 strcpy(buf2, buf1);
1099
1100                 // Parse line in a simple way
1101                 char *bvalue;
1102                 int len;
1103
1104                 len = strcspn(buf2, "\t =");
1105                 bvalue = buf2 + len;
1106                 bvalue += strspn(bvalue, "\t ");
1107                 if(*bvalue == '=') {
1108                         bvalue++;
1109                         bvalue += strspn(bvalue, "\t ");
1110                 }
1111                 rstrip(bvalue);
1112                 buf2[len] = '\0';
1113
1114                 // Did it match?
1115                 if(!strcasecmp(buf2, variable)) {
1116                         // Del
1117                         if(action < 0) {
1118                                 if(!*value || !strcasecmp(bvalue, value)) {
1119                                         removed = true;
1120                                         continue;
1121                                 }
1122                         // Set
1123                         } else if(action == 0) {
1124                                 // Already set? Delete the rest...
1125                                 if(set)
1126                                         continue;
1127                                 // Otherwise, replace.
1128                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1129                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1130                                         return 1;
1131                                 }
1132                                 set = true;
1133                                 continue;
1134                         }
1135                 }
1136
1137                 // Copy original line...
1138                 if(fputs(buf1, tf) < 0) {
1139                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1140                         return 1;
1141                 }
1142         }
1143
1144         // Make sure we read everything...
1145         if(ferror(f) || !feof(f)) {
1146                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1147                 return 1;
1148         }
1149
1150         if(fclose(f)) {
1151                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1152                 return 1;
1153         }
1154
1155         // Add new variable if necessary.
1156         if(action > 0 || (action == 0 && !set)) {
1157                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1158                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1159                         return 1;
1160                 }
1161         }
1162
1163         // Make sure we wrote everything...
1164         if(fclose(tf)) {
1165                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1166                 return 1;
1167         }
1168
1169         // Could we find what we had to remove?
1170         if(action < 0 && !removed) {
1171                 remove(tmpfile);
1172                 fprintf(stderr, "No configuration variables deleted.\n");
1173                 return *value;
1174         }
1175
1176         // Replace the configuration file with the new one
1177 #ifdef HAVE_MINGW
1178         if(remove(filename)) {
1179                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1180                 return 1;
1181         }
1182 #endif
1183         if(rename(tmpfile, filename)) {
1184                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1185                 return 1;
1186         }
1187
1188         // Silently try notifying a running tincd of changes.
1189         fclose(stderr);
1190
1191         if(connect_tincd())
1192                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1193
1194         return 0;
1195 }
1196
1197 bool check_id(const char *name) {
1198         for(int i = 0; i < strlen(name); i++) {
1199                 if(!isalnum(name[i]) && name[i] != '_')
1200                         return false;
1201         }
1202
1203         return true;
1204 }
1205
1206 static int cmd_init(int argc, char *argv[]) {
1207         if(!access(tinc_conf, F_OK)) {
1208                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1209                 return 1;
1210         }
1211
1212         if(argc < 2) {
1213                 if(isatty(0) && isatty(1)) {
1214                         char buf[1024];
1215                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1216                         fflush(stdout);
1217                         if(!fgets(buf, sizeof buf, stdin)) {
1218                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1219                                 return 1;
1220                         }
1221                         int len = rstrip(buf);
1222                         if(!len) {
1223                                 fprintf(stderr, "No name given!\n");
1224                                 return 1;
1225                         }
1226                         name = strdup(buf);
1227                 } else {
1228                         fprintf(stderr, "No Name given!\n");
1229                         return 1;
1230                 }
1231         } else {
1232                 name = strdup(argv[1]);
1233                 if(!*name) {
1234                         fprintf(stderr, "No Name given!\n");
1235                         return 1;
1236                 }
1237         }
1238
1239         if(!check_id(name)) {
1240                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1241                 return 1;
1242         }
1243
1244         if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1245                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1246                 return 1;
1247         }
1248
1249         if(mkdir(confbase, 0755) && errno != EEXIST) {
1250                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1251                 return 1;
1252         }
1253
1254         char *hosts_dir = NULL;
1255         xasprintf(&hosts_dir, "%s/hosts", confbase);
1256         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1257                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1258                 return 1;
1259         }
1260
1261         FILE *f = fopen(tinc_conf, "w");
1262         if(!f) {
1263                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1264                 return 1;
1265         }
1266
1267         fprintf(f, "Name = %s\n", name);
1268         fclose(f);
1269
1270         fclose(stdin);
1271         if(!rsa_keygen(2048) || !ecdsa_keygen())
1272                 return false;
1273
1274         return true;
1275
1276 }
1277
1278 static int cmd_generate_keys(int argc, char *argv[]) {
1279         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1280 }
1281
1282 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1283         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1284 }
1285
1286 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1287         return !ecdsa_keygen();
1288 }
1289
1290 static int cmd_help(int argc, char *argv[]) {
1291         usage(false);
1292         return 0;
1293 }
1294
1295 static int cmd_version(int argc, char *argv[]) {
1296         version();
1297         return 0;
1298 }
1299
1300 static int cmd_info(int argc, char *argv[]) {
1301         if(argc != 2) {
1302                 fprintf(stderr, "Invalid number of arguments.\n");
1303                 return 1;
1304         }
1305
1306         if(!connect_tincd())
1307                 return 1;
1308
1309         return info(fd, argv[1]);
1310 }
1311
1312 static const char *conffiles[] = {
1313         "tinc.conf",
1314         "tinc-up",
1315         "tinc-down",
1316         "subnet-up",
1317         "subnet-down",
1318         "host-up",
1319         "host-down",
1320         NULL,
1321 };
1322
1323 static int cmd_edit(int argc, char *argv[]) {
1324         if(argc != 2) {
1325                 fprintf(stderr, "Invalid number of arguments.\n");
1326                 return 1;
1327         }
1328
1329         char *filename = NULL;
1330
1331         if(strncmp(argv[1], "hosts/", 6)) {
1332                 for(int i = 0; conffiles[i]; i++) {
1333                         if(!strcmp(argv[1], conffiles[i])) {
1334                                 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1335                                 break;
1336                         }
1337                 }
1338         } else {
1339                 argv[1] += 6;
1340         }
1341
1342         if(!filename) {
1343                 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1344                 char *dash = strchr(argv[1], '-');
1345                 if(dash) {
1346                         *dash++ = 0;
1347                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1348                                 fprintf(stderr, "Invalid configuration filename.\n");
1349                                 return 1;
1350                         }
1351                 }
1352         }
1353
1354 #ifndef HAVE_MINGW
1355         char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1356 #else
1357         char *editor = "edit"
1358 #endif
1359
1360         char *command;
1361         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1362         int result = system(command);
1363         if(result)
1364                 return result;
1365
1366         // Silently try notifying a running tincd of changes.
1367         fclose(stderr);
1368
1369         if(connect_tincd())
1370                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1371
1372         return 0;
1373 }
1374
1375 static int export(const char *name, FILE *out) {
1376         char *filename;
1377         xasprintf(&filename, "%s/%s", hosts_dir, name);
1378         FILE *in = fopen(filename, "r");
1379         if(!in) {
1380                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1381                 return 1;
1382         }
1383
1384         fprintf(out, "Name = %s\n", name);
1385         char buf[4096];
1386         while(fgets(buf, sizeof buf, in))
1387                 fputs(buf, out);
1388
1389         if(ferror(in)) {
1390                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1391                 return 1;
1392         }
1393
1394         fclose(in);
1395         return 0;
1396 }
1397
1398 static int cmd_export(int argc, char *argv[]) {
1399         char *name = get_my_name();
1400         if(!name)
1401                 return 1;
1402
1403         return export(name, stdout);
1404 }
1405
1406 static int cmd_export_all(int argc, char *argv[]) {
1407         DIR *dir = opendir(hosts_dir);
1408         if(!dir) {
1409                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1410                 return 1;
1411         }
1412
1413         bool first = true;
1414         int result = 0;
1415         struct dirent *ent;
1416
1417         while((ent = readdir(dir))) {
1418                 if(!check_id(ent->d_name))
1419                         continue;
1420
1421                 if(first)
1422                         first = false;
1423                 else
1424                         printf("#---------------------------------------------------------------#\n");
1425
1426                 result |= export(ent->d_name, stdout);
1427         }
1428
1429         closedir(dir);
1430         return result;
1431 }
1432
1433 static int cmd_import(int argc, char *argv[]) {
1434         FILE *in = stdin;
1435         FILE *out = NULL;
1436
1437         char buf[4096];
1438         char name[4096];
1439         char *filename;
1440         int count = 0;
1441         bool firstline = true;
1442
1443         while(fgets(buf, sizeof buf, in)) {
1444                 if(sscanf(buf, "Name = %s", name) == 1) {
1445                         if(!check_id(name)) {
1446                                 fprintf(stderr, "Invalid Name in input!\n");
1447                                 return 1;
1448                         }
1449
1450                         if(out)
1451                                 fclose(out);
1452
1453                         free(filename);
1454                         xasprintf(&filename, "%s/%s", hosts_dir, name);
1455
1456                         if(!force && !access(filename, F_OK)) {
1457                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1458                                 out = NULL;
1459                                 continue;
1460                         }
1461
1462                         out = fopen(filename, "w");
1463                         if(!out) {
1464                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1465                                 return 1;
1466                         }
1467
1468                         count++;
1469                         firstline = false;
1470                         continue;
1471                 } else if(firstline) {
1472                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1473                         firstline = false;
1474                 }
1475
1476
1477                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1478                         continue;
1479
1480                 if(out) {
1481                         if(fputs(buf, out) < 0) {
1482                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1483                                 return 1;
1484                         }
1485                 }
1486         }
1487
1488         if(out)
1489                 fclose(out);
1490
1491         if(count) {
1492                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1493                 return 0;
1494         } else {
1495                 fprintf(stderr, "No host configuration files imported.\n");
1496                 return 1;
1497         }
1498 }
1499
1500 static const struct {
1501         const char *command;
1502         int (*function)(int argc, char *argv[]);
1503 } commands[] = {
1504         {"start", cmd_start},
1505         {"stop", cmd_stop},
1506         {"restart", cmd_restart},
1507         {"reload", cmd_reload},
1508         {"dump", cmd_dump},
1509         {"purge", cmd_purge},
1510         {"debug", cmd_debug},
1511         {"retry", cmd_retry},
1512         {"connect", cmd_connect},
1513         {"disconnect", cmd_disconnect},
1514         {"top", cmd_top},
1515         {"pcap", cmd_pcap},
1516         {"log", cmd_log},
1517         {"pid", cmd_pid},
1518         {"config", cmd_config},
1519         {"init", cmd_init},
1520         {"generate-keys", cmd_generate_keys},
1521         {"generate-rsa-keys", cmd_generate_rsa_keys},
1522         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1523         {"help", cmd_help},
1524         {"version", cmd_version},
1525         {"info", cmd_info},
1526         {"edit", cmd_edit},
1527         {"export", cmd_export},
1528         {"export-all", cmd_export_all},
1529         {"import", cmd_import},
1530         {NULL, NULL},
1531 };
1532
1533 int main(int argc, char *argv[]) {
1534         program_name = argv[0];
1535
1536         if(!parse_options(argc, argv))
1537                 return 1;
1538         
1539         make_names();
1540
1541         if(show_version) {
1542                 version();
1543                 return 0;
1544         }
1545
1546         if(show_help) {
1547                 usage(false);
1548                 return 0;
1549         }
1550
1551         if(optind >= argc) {
1552                 fprintf(stderr, "No command given.\n");
1553                 usage(true);
1554                 return 1;
1555         }
1556
1557         for(int i = 0; commands[i].command; i++) {
1558                 if(!strcasecmp(argv[optind], commands[i].command))
1559                         return commands[i].function(argc - optind, argv + optind);
1560         }
1561
1562         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1563         usage(true);
1564         return 1;
1565 }