Fix various compiler warnings.
[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                 xasprintf(&c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
693         else
694                 c = "tincd";
695
696         argv[0] = c;
697
698         for(i = j = 1; argv[i]; ++i)
699                 if (i != optind && strcmp(argv[i], "--") != 0)
700                         argv[j++] = argv[i];
701
702         argv[j] = NULL;
703         execvp(c, argv);
704         fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
705         return 1;
706 }
707
708 static int cmd_stop(int argc, char *argv[]) {
709 #ifndef HAVE_MINGW
710         if(!connect_tincd())
711                 return 1;
712
713         sendline(fd, "%d %d", CONTROL, REQ_STOP);
714         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
715                 fprintf(stderr, "Could not stop tinc daemon.\n");
716                 return 1;
717         }
718 #else
719         if(!remove_service())
720                 return 1;
721 #endif
722         return 0;
723 }
724
725 static int cmd_restart(int argc, char *argv[]) {
726         return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
727 }
728
729 static int cmd_reload(int argc, char *argv[]) {
730         if(!connect_tincd())
731                 return 1;
732
733         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
734         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
735                 fprintf(stderr, "Could not reload configuration.\n");
736                 return 1;
737         }
738
739         return 0;
740
741 }
742
743 static int cmd_dump(int argc, char *argv[]) {
744         if(argc != 2) {
745                 fprintf(stderr, "Invalid number of arguments.\n");
746                 usage(true);
747                 return 1;
748         }
749
750         if(!connect_tincd())
751                 return 1;
752
753         bool do_graph = false;
754
755         if(!strcasecmp(argv[1], "nodes"))
756                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
757         else if(!strcasecmp(argv[1], "edges"))
758                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
759         else if(!strcasecmp(argv[1], "subnets"))
760                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
761         else if(!strcasecmp(argv[1], "connections"))
762                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
763         else if(!strcasecmp(argv[1], "graph")) {
764                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
765                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
766                 do_graph = true;
767         } else {
768                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
769                 usage(true);
770                 return 1;
771         }
772
773         if(do_graph)
774                 printf("digraph {\n");
775
776         while(recvline(fd, line, sizeof line)) {
777                 char node1[4096], node2[4096];
778                 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
779                 if(n == 2) {
780                         if(do_graph && req == REQ_DUMP_NODES)
781                                 continue;
782                         else {
783                                 if(do_graph)
784                                         printf("}\n");
785                                 return 0;
786                         }
787                 }
788                 if(n < 2)
789                         break;
790
791                 if(!do_graph)
792                         printf("%s\n", line + 5);
793                 else {
794                         if(req == REQ_DUMP_NODES)
795                                 printf(" %s [label = \"%s\"];\n", node1, node1);
796                         else
797                                 printf(" %s -> %s;\n", node1, node2);
798                 }
799         }
800
801         fprintf(stderr, "Error receiving dump.\n");
802         return 1;
803 }
804
805 static int cmd_purge(int argc, char *argv[]) {
806         if(!connect_tincd())
807                 return 1;
808
809         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
810         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
811                 fprintf(stderr, "Could not purge old information.\n");
812                 return 1;
813         }
814
815         return 0;
816 }
817
818 static int cmd_debug(int argc, char *argv[]) {
819         if(argc != 2) {
820                 fprintf(stderr, "Invalid number of arguments.\n");
821                 return 1;
822         }
823
824         if(!connect_tincd())
825                 return 1;
826
827         int debuglevel = atoi(argv[1]);
828         int origlevel;
829
830         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
831         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
832                 fprintf(stderr, "Could not set debug level.\n");
833                 return 1;
834         }
835
836         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
837         return 0;
838 }
839
840 static int cmd_retry(int argc, char *argv[]) {
841         if(!connect_tincd())
842                 return 1;
843
844         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
845         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
846                 fprintf(stderr, "Could not retry outgoing connections.\n");
847                 return 1;
848         }
849
850         return 0;
851 }
852
853 static int cmd_connect(int argc, char *argv[]) {
854         if(argc != 2) {
855                 fprintf(stderr, "Invalid number of arguments.\n");
856                 return 1;
857         }
858
859         if(!check_id(argv[2])) {
860                 fprintf(stderr, "Invalid name for node.\n");
861                 return 1;
862         }
863
864         if(!connect_tincd())
865                 return 1;
866
867         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
868         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
869                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
870                 return 1;
871         }
872
873         return 0;
874 }
875
876 static int cmd_disconnect(int argc, char *argv[]) {
877         if(argc != 2) {
878                 fprintf(stderr, "Invalid number of arguments.\n");
879                 return 1;
880         }
881
882         if(!check_id(argv[2])) {
883                 fprintf(stderr, "Invalid name for node.\n");
884                 return 1;
885         }
886
887         if(!connect_tincd())
888                 return 1;
889
890         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
891         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
892                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
893                 return 1;
894         }
895
896         return 0;
897 }
898
899 static int cmd_top(int argc, char *argv[]) {
900 #ifdef HAVE_CURSES
901         if(!connect_tincd())
902                 return 1;
903
904         top(fd);
905         return 0;
906 #else
907         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
908         return 1;
909 #endif
910 }
911
912 static int cmd_pcap(int argc, char *argv[]) {
913         if(!connect_tincd())
914                 return 1;
915
916         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
917         return 0;
918 }
919
920 static int cmd_log(int argc, char *argv[]) {
921         if(!connect_tincd())
922                 return 1;
923
924         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
925         return 0;
926 }
927
928 static int cmd_pid(int argc, char *argv[]) {
929         if(!connect_tincd())
930                 return 1;
931
932         printf("%d\n", pid);
933         return 0;
934 }
935
936 static int rstrip(char *value) {
937         int len = strlen(value);
938         while(len && strchr("\t\r\n ", value[len - 1]))
939                 value[--len] = 0;
940         return len;
941 }
942
943 static char *get_my_name() {
944         FILE *f = fopen(tinc_conf, "r");
945         if(!f) {
946                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
947                 return NULL;
948         }
949
950         char buf[4096];
951         char *value;
952         while(fgets(buf, sizeof buf, f)) {
953                 int len = strcspn(buf, "\t =");
954                 value = buf + len;
955                 value += strspn(value, "\t ");
956                 if(*value == '=') {
957                         value++;
958                         value += strspn(value, "\t ");
959                 }
960                 if(!rstrip(value))
961                         continue;
962                 buf[len] = 0;
963                 if(strcasecmp(buf, "Name"))
964                         continue;
965                 if(*value) {
966                         fclose(f);
967                         return strdup(value);
968                 }
969         }
970
971         fclose(f);
972         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
973         return NULL;
974 }
975
976 static char *hostvariables[] = {
977         "Address",
978         "Port",
979         "PublicKey",
980         "Subnet",
981         NULL,
982 };
983
984 static int cmd_config(int argc, char *argv[]) {
985         if(argc < 2) {
986                 fprintf(stderr, "Invalid number of arguments.\n");
987                 return 1;
988         }
989
990         int action = 0;
991         if(!strcasecmp(argv[1], "add")) {
992                 argv++, argc--, action = 1;
993         } else if(!strcasecmp(argv[1], "del")) {
994                 argv++, argc--, action = -1;
995         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
996                 argv++, argc--, action = 0;
997         }
998
999         if(argc < 2) {
1000                 fprintf(stderr, "Invalid number of arguments.\n");
1001                 return 1;
1002         }
1003
1004         // Concatenate the rest of the command line
1005         strncpy(line, argv[1], sizeof line - 1);
1006         for(int i = 2; i < argc; i++) {
1007                 strncat(line, " ", sizeof line - 1 - strlen(line));
1008                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1009         }
1010
1011         // Liberal parsing into node name, variable name and value.
1012         char *node = NULL;
1013         char *variable;
1014         char *value;
1015         int len;
1016
1017         len = strcspn(line, "\t =");
1018         value = line + len;
1019         value += strspn(value, "\t ");
1020         if(*value == '=') {
1021                 value++;
1022                 value += strspn(value, "\t ");
1023         }
1024         line[len] = '\0';
1025         variable = strchr(line, '.');
1026         if(variable) {
1027                 node = line;
1028                 *variable++ = 0;
1029         } else {
1030                 variable = line;
1031         }
1032
1033         if(!*variable) {
1034                 fprintf(stderr, "No variable given.\n");
1035                 return 1;
1036         }
1037
1038         if(action >= 0 && !*value) {
1039                 fprintf(stderr, "No value for variable given.\n");
1040                 return 1;
1041         }
1042
1043         // Should this go into our own host config file?
1044         if(!node) {
1045                 for(int i = 0; hostvariables[i]; i++) {
1046                         if(!strcasecmp(hostvariables[i], variable)) {
1047                                 node = get_my_name();
1048                                 if(!node)
1049                                         return 1;
1050                                 break;
1051                         }
1052                 }
1053         }
1054
1055         if(node && !check_id(node)) {
1056                 fprintf(stderr, "Invalid name for node.\n");
1057                 return 1;
1058         }
1059
1060         // Open the right configuration file.
1061         char *filename;
1062         if(node)
1063                 xasprintf(&filename, "%s/%s", hosts_dir, node);
1064         else
1065                 filename = tinc_conf;
1066
1067         FILE *f = fopen(filename, "r");
1068         if(!f) {
1069                 if(action < 0 || errno != ENOENT) {
1070                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1071                         return 1;
1072                 }
1073
1074                 // If it doesn't exist, create it.
1075                 f = fopen(filename, "a+");
1076                 if(!f) {
1077                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1078                         return 1;
1079                 } else {
1080                         fprintf(stderr, "Created configuration file %s.\n", filename);
1081                 }
1082         }
1083
1084         char *tmpfile;
1085         xasprintf(&tmpfile, "%s.config.tmp", filename);
1086         FILE *tf = fopen(tmpfile, "w");
1087         if(!tf) {
1088                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1089                 return 1;
1090         }
1091
1092         // Copy the file, making modifications on the fly.
1093         char buf1[4096];
1094         char buf2[4096];
1095         bool set = false;
1096         bool removed = false;
1097
1098         while(fgets(buf1, sizeof buf1, f)) {
1099                 buf1[sizeof buf1 - 1] = 0;
1100                 strcpy(buf2, buf1);
1101
1102                 // Parse line in a simple way
1103                 char *bvalue;
1104                 int len;
1105
1106                 len = strcspn(buf2, "\t =");
1107                 bvalue = buf2 + len;
1108                 bvalue += strspn(bvalue, "\t ");
1109                 if(*bvalue == '=') {
1110                         bvalue++;
1111                         bvalue += strspn(bvalue, "\t ");
1112                 }
1113                 rstrip(bvalue);
1114                 buf2[len] = '\0';
1115
1116                 // Did it match?
1117                 if(!strcasecmp(buf2, variable)) {
1118                         // Del
1119                         if(action < 0) {
1120                                 if(!*value || !strcasecmp(bvalue, value)) {
1121                                         removed = true;
1122                                         continue;
1123                                 }
1124                         // Set
1125                         } else if(action == 0) {
1126                                 // Already set? Delete the rest...
1127                                 if(set)
1128                                         continue;
1129                                 // Otherwise, replace.
1130                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1131                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1132                                         return 1;
1133                                 }
1134                                 set = true;
1135                                 continue;
1136                         }
1137                 }
1138
1139                 // Copy original line...
1140                 if(fputs(buf1, tf) < 0) {
1141                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1142                         return 1;
1143                 }
1144         }
1145
1146         // Make sure we read everything...
1147         if(ferror(f) || !feof(f)) {
1148                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1149                 return 1;
1150         }
1151
1152         if(fclose(f)) {
1153                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1154                 return 1;
1155         }
1156
1157         // Add new variable if necessary.
1158         if(action > 0 || (action == 0 && !set)) {
1159                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1160                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1161                         return 1;
1162                 }
1163         }
1164
1165         // Make sure we wrote everything...
1166         if(fclose(tf)) {
1167                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1168                 return 1;
1169         }
1170
1171         // Could we find what we had to remove?
1172         if(action < 0 && !removed) {
1173                 remove(tmpfile);
1174                 fprintf(stderr, "No configuration variables deleted.\n");
1175                 return *value;
1176         }
1177
1178         // Replace the configuration file with the new one
1179 #ifdef HAVE_MINGW
1180         if(remove(filename)) {
1181                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1182                 return 1;
1183         }
1184 #endif
1185         if(rename(tmpfile, filename)) {
1186                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1187                 return 1;
1188         }
1189
1190         // Silently try notifying a running tincd of changes.
1191         fclose(stderr);
1192
1193         if(connect_tincd())
1194                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1195
1196         return 0;
1197 }
1198
1199 bool check_id(const char *name) {
1200         for(int i = 0; i < strlen(name); i++) {
1201                 if(!isalnum(name[i]) && name[i] != '_')
1202                         return false;
1203         }
1204
1205         return true;
1206 }
1207
1208 static int cmd_init(int argc, char *argv[]) {
1209         if(!access(tinc_conf, F_OK)) {
1210                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1211                 return 1;
1212         }
1213
1214         if(argc < 2) {
1215                 if(isatty(0) && isatty(1)) {
1216                         char buf[1024];
1217                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1218                         fflush(stdout);
1219                         if(!fgets(buf, sizeof buf, stdin)) {
1220                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1221                                 return 1;
1222                         }
1223                         int len = rstrip(buf);
1224                         if(!len) {
1225                                 fprintf(stderr, "No name given!\n");
1226                                 return 1;
1227                         }
1228                         name = strdup(buf);
1229                 } else {
1230                         fprintf(stderr, "No Name given!\n");
1231                         return 1;
1232                 }
1233         } else {
1234                 name = strdup(argv[1]);
1235                 if(!*name) {
1236                         fprintf(stderr, "No Name given!\n");
1237                         return 1;
1238                 }
1239         }
1240
1241         if(!check_id(name)) {
1242                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1243                 return 1;
1244         }
1245
1246         if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1247                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1248                 return 1;
1249         }
1250
1251         if(mkdir(confbase, 0755) && errno != EEXIST) {
1252                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1253                 return 1;
1254         }
1255
1256         char *hosts_dir = NULL;
1257         xasprintf(&hosts_dir, "%s/hosts", confbase);
1258         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1259                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1260                 return 1;
1261         }
1262
1263         FILE *f = fopen(tinc_conf, "w");
1264         if(!f) {
1265                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1266                 return 1;
1267         }
1268
1269         fprintf(f, "Name = %s\n", name);
1270         fclose(f);
1271
1272         fclose(stdin);
1273         if(!rsa_keygen(2048) || !ecdsa_keygen())
1274                 return false;
1275
1276         return true;
1277
1278 }
1279
1280 static int cmd_generate_keys(int argc, char *argv[]) {
1281         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1282 }
1283
1284 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1285         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1286 }
1287
1288 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1289         return !ecdsa_keygen();
1290 }
1291
1292 static int cmd_help(int argc, char *argv[]) {
1293         usage(false);
1294         return 0;
1295 }
1296
1297 static int cmd_version(int argc, char *argv[]) {
1298         version();
1299         return 0;
1300 }
1301
1302 static int cmd_info(int argc, char *argv[]) {
1303         if(argc != 2) {
1304                 fprintf(stderr, "Invalid number of arguments.\n");
1305                 return 1;
1306         }
1307
1308         if(!connect_tincd())
1309                 return 1;
1310
1311         return info(fd, argv[1]);
1312 }
1313
1314 static const char *conffiles[] = {
1315         "tinc.conf",
1316         "tinc-up",
1317         "tinc-down",
1318         "subnet-up",
1319         "subnet-down",
1320         "host-up",
1321         "host-down",
1322         NULL,
1323 };
1324
1325 static int cmd_edit(int argc, char *argv[]) {
1326         if(argc != 2) {
1327                 fprintf(stderr, "Invalid number of arguments.\n");
1328                 return 1;
1329         }
1330
1331         char *filename = NULL;
1332
1333         if(strncmp(argv[1], "hosts/", 6)) {
1334                 for(int i = 0; conffiles[i]; i++) {
1335                         if(!strcmp(argv[1], conffiles[i])) {
1336                                 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1337                                 break;
1338                         }
1339                 }
1340         } else {
1341                 argv[1] += 6;
1342         }
1343
1344         if(!filename) {
1345                 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1346                 char *dash = strchr(argv[1], '-');
1347                 if(dash) {
1348                         *dash++ = 0;
1349                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1350                                 fprintf(stderr, "Invalid configuration filename.\n");
1351                                 return 1;
1352                         }
1353                 }
1354         }
1355
1356 #ifndef HAVE_MINGW
1357         char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1358 #else
1359         char *editor = "edit";
1360 #endif
1361
1362         char *command;
1363         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1364         int result = system(command);
1365         if(result)
1366                 return result;
1367
1368         // Silently try notifying a running tincd of changes.
1369         fclose(stderr);
1370
1371         if(connect_tincd())
1372                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1373
1374         return 0;
1375 }
1376
1377 static int export(const char *name, FILE *out) {
1378         char *filename;
1379         xasprintf(&filename, "%s/%s", hosts_dir, name);
1380         FILE *in = fopen(filename, "r");
1381         if(!in) {
1382                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1383                 return 1;
1384         }
1385
1386         fprintf(out, "Name = %s\n", name);
1387         char buf[4096];
1388         while(fgets(buf, sizeof buf, in)) {
1389                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1390                         fputs(buf, out);
1391         }
1392
1393         if(ferror(in)) {
1394                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1395                 return 1;
1396         }
1397
1398         fclose(in);
1399         return 0;
1400 }
1401
1402 static int cmd_export(int argc, char *argv[]) {
1403         char *name = get_my_name();
1404         if(!name)
1405                 return 1;
1406
1407         return export(name, stdout);
1408 }
1409
1410 static int cmd_export_all(int argc, char *argv[]) {
1411         DIR *dir = opendir(hosts_dir);
1412         if(!dir) {
1413                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1414                 return 1;
1415         }
1416
1417         bool first = true;
1418         int result = 0;
1419         struct dirent *ent;
1420
1421         while((ent = readdir(dir))) {
1422                 if(!check_id(ent->d_name))
1423                         continue;
1424
1425                 if(first)
1426                         first = false;
1427                 else
1428                         printf("#---------------------------------------------------------------#\n");
1429
1430                 result |= export(ent->d_name, stdout);
1431         }
1432
1433         closedir(dir);
1434         return result;
1435 }
1436
1437 static int cmd_import(int argc, char *argv[]) {
1438         FILE *in = stdin;
1439         FILE *out = NULL;
1440
1441         char buf[4096];
1442         char name[4096];
1443         char *filename;
1444         int count = 0;
1445         bool firstline = true;
1446
1447         while(fgets(buf, sizeof buf, in)) {
1448                 if(sscanf(buf, "Name = %s", name) == 1) {
1449                         if(!check_id(name)) {
1450                                 fprintf(stderr, "Invalid Name in input!\n");
1451                                 return 1;
1452                         }
1453
1454                         if(out)
1455                                 fclose(out);
1456
1457                         free(filename);
1458                         xasprintf(&filename, "%s/%s", hosts_dir, name);
1459
1460                         if(!force && !access(filename, F_OK)) {
1461                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1462                                 out = NULL;
1463                                 continue;
1464                         }
1465
1466                         out = fopen(filename, "w");
1467                         if(!out) {
1468                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1469                                 return 1;
1470                         }
1471
1472                         count++;
1473                         firstline = false;
1474                         continue;
1475                 } else if(firstline) {
1476                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1477                         firstline = false;
1478                 }
1479
1480
1481                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1482                         continue;
1483
1484                 if(out) {
1485                         if(fputs(buf, out) < 0) {
1486                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1487                                 return 1;
1488                         }
1489                 }
1490         }
1491
1492         if(out)
1493                 fclose(out);
1494
1495         if(count) {
1496                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1497                 return 0;
1498         } else {
1499                 fprintf(stderr, "No host configuration files imported.\n");
1500                 return 1;
1501         }
1502 }
1503
1504 static const struct {
1505         const char *command;
1506         int (*function)(int argc, char *argv[]);
1507 } commands[] = {
1508         {"start", cmd_start},
1509         {"stop", cmd_stop},
1510         {"restart", cmd_restart},
1511         {"reload", cmd_reload},
1512         {"dump", cmd_dump},
1513         {"purge", cmd_purge},
1514         {"debug", cmd_debug},
1515         {"retry", cmd_retry},
1516         {"connect", cmd_connect},
1517         {"disconnect", cmd_disconnect},
1518         {"top", cmd_top},
1519         {"pcap", cmd_pcap},
1520         {"log", cmd_log},
1521         {"pid", cmd_pid},
1522         {"config", cmd_config},
1523         {"init", cmd_init},
1524         {"generate-keys", cmd_generate_keys},
1525         {"generate-rsa-keys", cmd_generate_rsa_keys},
1526         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1527         {"help", cmd_help},
1528         {"version", cmd_version},
1529         {"info", cmd_info},
1530         {"edit", cmd_edit},
1531         {"export", cmd_export},
1532         {"export-all", cmd_export_all},
1533         {"import", cmd_import},
1534         {NULL, NULL},
1535 };
1536
1537 int main(int argc, char *argv[]) {
1538         program_name = argv[0];
1539
1540         if(!parse_options(argc, argv))
1541                 return 1;
1542         
1543         make_names();
1544
1545         if(show_version) {
1546                 version();
1547                 return 0;
1548         }
1549
1550         if(show_help) {
1551                 usage(false);
1552                 return 0;
1553         }
1554
1555         if(optind >= argc) {
1556                 fprintf(stderr, "No command given.\n");
1557                 usage(true);
1558                 return 1;
1559         }
1560
1561         for(int i = 0; commands[i].command; i++) {
1562                 if(!strcasecmp(argv[optind], commands[i].command))
1563                         return commands[i].function(argc - optind, argv + optind);
1564         }
1565
1566         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1567         usage(true);
1568         return 1;
1569 }