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