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