Add some checks when changing configuration.
[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 #define VAR_SERVER 1    /* Should be in tinc.conf */
977 #define VAR_HOST 2      /* Can be in host config file */
978 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
979 #define VAR_OBSOLETE 8  /* Should not be used anymore */
980
981 static struct {
982         const char *name;
983         int type;
984 } const variables[] = {
985         /* Server configuration */
986         {"AddressFamily", VAR_SERVER},
987         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
988         {"BindToInterface", VAR_SERVER},
989         {"Broadcast", VAR_SERVER},
990         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
991         {"DecrementTTL", VAR_SERVER},
992         {"Device", VAR_SERVER},
993         {"DeviceType", VAR_SERVER},
994         {"DirectOnly", VAR_SERVER},
995         {"ECDSAPrivateKeyFile", VAR_SERVER},
996         {"ExperimentalProtocol", VAR_SERVER},
997         {"Forwarding", VAR_SERVER},
998         {"GraphDumpFile", VAR_SERVER},
999         {"Hostnames", VAR_SERVER},
1000         {"IffOneQueue", VAR_SERVER},
1001         {"Interface", VAR_SERVER},
1002         {"KeyExpire", VAR_SERVER},
1003         {"LocalDiscovery", VAR_SERVER},
1004         {"MACExpire", VAR_SERVER},
1005         {"MaxTimeout", VAR_SERVER},
1006         {"Mode", VAR_SERVER},
1007         {"Name", VAR_SERVER},
1008         {"PingInterval", VAR_SERVER},
1009         {"PingTimeout", VAR_SERVER},
1010         {"PriorityInheritance", VAR_SERVER},
1011         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1012         {"PrivateKeyFile", VAR_SERVER},
1013         {"ProcessPriority", VAR_SERVER},
1014         {"ReplayWindow", VAR_SERVER},
1015         {"StrictSubnets", VAR_SERVER},
1016         {"TunnelServer", VAR_SERVER},
1017         {"UDPRcvBuf", VAR_SERVER},
1018         {"UDPSndBuf", VAR_SERVER},
1019         /* Host configuration */
1020         {"Address", VAR_HOST | VAR_MULTIPLE},
1021         {"Cipher", VAR_SERVER | VAR_HOST},
1022         {"ClampMSS", VAR_SERVER | VAR_HOST},
1023         {"Compression", VAR_SERVER | VAR_HOST},
1024         {"Digest", VAR_SERVER | VAR_HOST},
1025         {"IndirectData", VAR_SERVER | VAR_HOST},
1026         {"MACLength", VAR_SERVER | VAR_HOST},
1027         {"PMTU", VAR_SERVER | VAR_HOST},
1028         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1029         {"Port", VAR_HOST},
1030         {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1031         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1032         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1033         {"TCPOnly", VAR_SERVER | VAR_HOST},
1034         {NULL, 0}
1035 };
1036
1037 static int cmd_config(int argc, char *argv[]) {
1038         if(argc < 2) {
1039                 fprintf(stderr, "Invalid number of arguments.\n");
1040                 return 1;
1041         }
1042
1043         int action = 0;
1044         if(!strcasecmp(argv[1], "add")) {
1045                 argv++, argc--, action = 1;
1046         } else if(!strcasecmp(argv[1], "del")) {
1047                 argv++, argc--, action = -1;
1048         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1049                 argv++, argc--, action = 0;
1050         }
1051
1052         if(argc < 2) {
1053                 fprintf(stderr, "Invalid number of arguments.\n");
1054                 return 1;
1055         }
1056
1057         // Concatenate the rest of the command line
1058         strncpy(line, argv[1], sizeof line - 1);
1059         for(int i = 2; i < argc; i++) {
1060                 strncat(line, " ", sizeof line - 1 - strlen(line));
1061                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1062         }
1063
1064         // Liberal parsing into node name, variable name and value.
1065         char *node = NULL;
1066         char *variable;
1067         char *value;
1068         int len;
1069
1070         len = strcspn(line, "\t =");
1071         value = line + len;
1072         value += strspn(value, "\t ");
1073         if(*value == '=') {
1074                 value++;
1075                 value += strspn(value, "\t ");
1076         }
1077         line[len] = '\0';
1078         variable = strchr(line, '.');
1079         if(variable) {
1080                 node = line;
1081                 *variable++ = 0;
1082         } else {
1083                 variable = line;
1084         }
1085
1086         if(!*variable) {
1087                 fprintf(stderr, "No variable given.\n");
1088                 return 1;
1089         }
1090
1091         if(action >= 0 && !*value) {
1092                 fprintf(stderr, "No value for variable given.\n");
1093                 return 1;
1094         }
1095
1096         /* Some simple checks. */
1097         bool found = false;
1098
1099         for(int i = 0; variables[i].name; i++) {
1100                 if(strcasecmp(variables[i].name, variable))
1101                         continue;
1102
1103                 found = true;
1104                 variable = (char *)variables[i].name;
1105
1106                 /* Discourage use of obsolete variables. */
1107
1108                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1109                         if(force) {
1110                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1111                         } else {
1112                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1113                                 return 1;
1114                         }
1115                 }
1116
1117                 /* Don't put server variables in host config files */
1118
1119                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1120                         if(force) {
1121                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1122                         } else {
1123                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1124                                 return 1;
1125                         }
1126                 }
1127
1128                 /* Should this go into our own host config file? */
1129
1130                 if(!node && !(variables[i].type & VAR_SERVER)) {
1131                         node = get_my_name();
1132                         if(!node)
1133                                 return 1;
1134                 }
1135
1136                 break;
1137         }
1138
1139         if(node && !check_id(node)) {
1140                 fprintf(stderr, "Invalid name for node.\n");
1141                 return 1;
1142         }
1143
1144         if(!found && action >= 0) {
1145                 if(force) {
1146                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1147                 } else {
1148                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1149                         return 1;
1150                 }
1151         }
1152
1153         // Open the right configuration file.
1154         char *filename;
1155         if(node)
1156                 xasprintf(&filename, "%s/%s", hosts_dir, node);
1157         else
1158                 filename = tinc_conf;
1159
1160         FILE *f = fopen(filename, "r");
1161         if(!f) {
1162                 if(action < 0 || errno != ENOENT) {
1163                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1164                         return 1;
1165                 }
1166
1167                 // If it doesn't exist, create it.
1168                 f = fopen(filename, "a+");
1169                 if(!f) {
1170                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1171                         return 1;
1172                 } else {
1173                         fprintf(stderr, "Created configuration file %s.\n", filename);
1174                 }
1175         }
1176
1177         char *tmpfile;
1178         xasprintf(&tmpfile, "%s.config.tmp", filename);
1179         FILE *tf = fopen(tmpfile, "w");
1180         if(!tf) {
1181                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1182                 return 1;
1183         }
1184
1185         // Copy the file, making modifications on the fly.
1186         char buf1[4096];
1187         char buf2[4096];
1188         bool set = false;
1189         bool removed = false;
1190
1191         while(fgets(buf1, sizeof buf1, f)) {
1192                 buf1[sizeof buf1 - 1] = 0;
1193                 strcpy(buf2, buf1);
1194
1195                 // Parse line in a simple way
1196                 char *bvalue;
1197                 int len;
1198
1199                 len = strcspn(buf2, "\t =");
1200                 bvalue = buf2 + len;
1201                 bvalue += strspn(bvalue, "\t ");
1202                 if(*bvalue == '=') {
1203                         bvalue++;
1204                         bvalue += strspn(bvalue, "\t ");
1205                 }
1206                 rstrip(bvalue);
1207                 buf2[len] = '\0';
1208
1209                 // Did it match?
1210                 if(!strcasecmp(buf2, variable)) {
1211                         // Del
1212                         if(action < 0) {
1213                                 if(!*value || !strcasecmp(bvalue, value)) {
1214                                         removed = true;
1215                                         continue;
1216                                 }
1217                         // Set
1218                         } else if(action == 0) {
1219                                 // Already set? Delete the rest...
1220                                 if(set)
1221                                         continue;
1222                                 // Otherwise, replace.
1223                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1224                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1225                                         return 1;
1226                                 }
1227                                 set = true;
1228                                 continue;
1229                         }
1230                 }
1231
1232                 // Copy original line...
1233                 if(fputs(buf1, tf) < 0) {
1234                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1235                         return 1;
1236                 }
1237         }
1238
1239         // Make sure we read everything...
1240         if(ferror(f) || !feof(f)) {
1241                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1242                 return 1;
1243         }
1244
1245         if(fclose(f)) {
1246                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1247                 return 1;
1248         }
1249
1250         // Add new variable if necessary.
1251         if(action > 0 || (action == 0 && !set)) {
1252                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1253                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1254                         return 1;
1255                 }
1256         }
1257
1258         // Make sure we wrote everything...
1259         if(fclose(tf)) {
1260                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1261                 return 1;
1262         }
1263
1264         // Could we find what we had to remove?
1265         if(action < 0 && !removed) {
1266                 remove(tmpfile);
1267                 fprintf(stderr, "No configuration variables deleted.\n");
1268                 return *value;
1269         }
1270
1271         // Replace the configuration file with the new one
1272 #ifdef HAVE_MINGW
1273         if(remove(filename)) {
1274                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1275                 return 1;
1276         }
1277 #endif
1278         if(rename(tmpfile, filename)) {
1279                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1280                 return 1;
1281         }
1282
1283         // Silently try notifying a running tincd of changes.
1284         fclose(stderr);
1285
1286         if(connect_tincd())
1287                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1288
1289         return 0;
1290 }
1291
1292 bool check_id(const char *name) {
1293         for(int i = 0; i < strlen(name); i++) {
1294                 if(!isalnum(name[i]) && name[i] != '_')
1295                         return false;
1296         }
1297
1298         return true;
1299 }
1300
1301 static int cmd_init(int argc, char *argv[]) {
1302         if(!access(tinc_conf, F_OK)) {
1303                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1304                 return 1;
1305         }
1306
1307         if(argc < 2) {
1308                 if(isatty(0) && isatty(1)) {
1309                         char buf[1024];
1310                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1311                         fflush(stdout);
1312                         if(!fgets(buf, sizeof buf, stdin)) {
1313                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1314                                 return 1;
1315                         }
1316                         int len = rstrip(buf);
1317                         if(!len) {
1318                                 fprintf(stderr, "No name given!\n");
1319                                 return 1;
1320                         }
1321                         name = strdup(buf);
1322                 } else {
1323                         fprintf(stderr, "No Name given!\n");
1324                         return 1;
1325                 }
1326         } else {
1327                 name = strdup(argv[1]);
1328                 if(!*name) {
1329                         fprintf(stderr, "No Name given!\n");
1330                         return 1;
1331                 }
1332         }
1333
1334         if(!check_id(name)) {
1335                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1336                 return 1;
1337         }
1338
1339         if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1340                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1341                 return 1;
1342         }
1343
1344         if(mkdir(confbase, 0755) && errno != EEXIST) {
1345                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1346                 return 1;
1347         }
1348
1349         char *hosts_dir = NULL;
1350         xasprintf(&hosts_dir, "%s/hosts", confbase);
1351         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1352                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1353                 return 1;
1354         }
1355
1356         FILE *f = fopen(tinc_conf, "w");
1357         if(!f) {
1358                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1359                 return 1;
1360         }
1361
1362         fprintf(f, "Name = %s\n", name);
1363         fclose(f);
1364
1365         fclose(stdin);
1366         if(!rsa_keygen(2048) || !ecdsa_keygen())
1367                 return false;
1368
1369         return true;
1370
1371 }
1372
1373 static int cmd_generate_keys(int argc, char *argv[]) {
1374         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1375 }
1376
1377 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1378         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1379 }
1380
1381 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1382         return !ecdsa_keygen();
1383 }
1384
1385 static int cmd_help(int argc, char *argv[]) {
1386         usage(false);
1387         return 0;
1388 }
1389
1390 static int cmd_version(int argc, char *argv[]) {
1391         version();
1392         return 0;
1393 }
1394
1395 static int cmd_info(int argc, char *argv[]) {
1396         if(argc != 2) {
1397                 fprintf(stderr, "Invalid number of arguments.\n");
1398                 return 1;
1399         }
1400
1401         if(!connect_tincd())
1402                 return 1;
1403
1404         return info(fd, argv[1]);
1405 }
1406
1407 static const char *conffiles[] = {
1408         "tinc.conf",
1409         "tinc-up",
1410         "tinc-down",
1411         "subnet-up",
1412         "subnet-down",
1413         "host-up",
1414         "host-down",
1415         NULL,
1416 };
1417
1418 static int cmd_edit(int argc, char *argv[]) {
1419         if(argc != 2) {
1420                 fprintf(stderr, "Invalid number of arguments.\n");
1421                 return 1;
1422         }
1423
1424         char *filename = NULL;
1425
1426         if(strncmp(argv[1], "hosts/", 6)) {
1427                 for(int i = 0; conffiles[i]; i++) {
1428                         if(!strcmp(argv[1], conffiles[i])) {
1429                                 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1430                                 break;
1431                         }
1432                 }
1433         } else {
1434                 argv[1] += 6;
1435         }
1436
1437         if(!filename) {
1438                 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1439                 char *dash = strchr(argv[1], '-');
1440                 if(dash) {
1441                         *dash++ = 0;
1442                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1443                                 fprintf(stderr, "Invalid configuration filename.\n");
1444                                 return 1;
1445                         }
1446                 }
1447         }
1448
1449 #ifndef HAVE_MINGW
1450         char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1451 #else
1452         char *editor = "edit";
1453 #endif
1454
1455         char *command;
1456         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1457         int result = system(command);
1458         if(result)
1459                 return result;
1460
1461         // Silently try notifying a running tincd of changes.
1462         fclose(stderr);
1463
1464         if(connect_tincd())
1465                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1466
1467         return 0;
1468 }
1469
1470 static int export(const char *name, FILE *out) {
1471         char *filename;
1472         xasprintf(&filename, "%s/%s", hosts_dir, name);
1473         FILE *in = fopen(filename, "r");
1474         if(!in) {
1475                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1476                 return 1;
1477         }
1478
1479         fprintf(out, "Name = %s\n", name);
1480         char buf[4096];
1481         while(fgets(buf, sizeof buf, in)) {
1482                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1483                         fputs(buf, out);
1484         }
1485
1486         if(ferror(in)) {
1487                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1488                 return 1;
1489         }
1490
1491         fclose(in);
1492         return 0;
1493 }
1494
1495 static int cmd_export(int argc, char *argv[]) {
1496         char *name = get_my_name();
1497         if(!name)
1498                 return 1;
1499
1500         return export(name, stdout);
1501 }
1502
1503 static int cmd_export_all(int argc, char *argv[]) {
1504         DIR *dir = opendir(hosts_dir);
1505         if(!dir) {
1506                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1507                 return 1;
1508         }
1509
1510         bool first = true;
1511         int result = 0;
1512         struct dirent *ent;
1513
1514         while((ent = readdir(dir))) {
1515                 if(!check_id(ent->d_name))
1516                         continue;
1517
1518                 if(first)
1519                         first = false;
1520                 else
1521                         printf("#---------------------------------------------------------------#\n");
1522
1523                 result |= export(ent->d_name, stdout);
1524         }
1525
1526         closedir(dir);
1527         return result;
1528 }
1529
1530 static int cmd_import(int argc, char *argv[]) {
1531         FILE *in = stdin;
1532         FILE *out = NULL;
1533
1534         char buf[4096];
1535         char name[4096];
1536         char *filename;
1537         int count = 0;
1538         bool firstline = true;
1539
1540         while(fgets(buf, sizeof buf, in)) {
1541                 if(sscanf(buf, "Name = %s", name) == 1) {
1542                         if(!check_id(name)) {
1543                                 fprintf(stderr, "Invalid Name in input!\n");
1544                                 return 1;
1545                         }
1546
1547                         if(out)
1548                                 fclose(out);
1549
1550                         free(filename);
1551                         xasprintf(&filename, "%s/%s", hosts_dir, name);
1552
1553                         if(!force && !access(filename, F_OK)) {
1554                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1555                                 out = NULL;
1556                                 continue;
1557                         }
1558
1559                         out = fopen(filename, "w");
1560                         if(!out) {
1561                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1562                                 return 1;
1563                         }
1564
1565                         count++;
1566                         firstline = false;
1567                         continue;
1568                 } else if(firstline) {
1569                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1570                         firstline = false;
1571                 }
1572
1573
1574                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1575                         continue;
1576
1577                 if(out) {
1578                         if(fputs(buf, out) < 0) {
1579                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1580                                 return 1;
1581                         }
1582                 }
1583         }
1584
1585         if(out)
1586                 fclose(out);
1587
1588         if(count) {
1589                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1590                 return 0;
1591         } else {
1592                 fprintf(stderr, "No host configuration files imported.\n");
1593                 return 1;
1594         }
1595 }
1596
1597 static const struct {
1598         const char *command;
1599         int (*function)(int argc, char *argv[]);
1600 } commands[] = {
1601         {"start", cmd_start},
1602         {"stop", cmd_stop},
1603         {"restart", cmd_restart},
1604         {"reload", cmd_reload},
1605         {"dump", cmd_dump},
1606         {"purge", cmd_purge},
1607         {"debug", cmd_debug},
1608         {"retry", cmd_retry},
1609         {"connect", cmd_connect},
1610         {"disconnect", cmd_disconnect},
1611         {"top", cmd_top},
1612         {"pcap", cmd_pcap},
1613         {"log", cmd_log},
1614         {"pid", cmd_pid},
1615         {"config", cmd_config},
1616         {"init", cmd_init},
1617         {"generate-keys", cmd_generate_keys},
1618         {"generate-rsa-keys", cmd_generate_rsa_keys},
1619         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1620         {"help", cmd_help},
1621         {"version", cmd_version},
1622         {"info", cmd_info},
1623         {"edit", cmd_edit},
1624         {"export", cmd_export},
1625         {"export-all", cmd_export_all},
1626         {"import", cmd_import},
1627         {NULL, NULL},
1628 };
1629
1630 int main(int argc, char *argv[]) {
1631         program_name = argv[0];
1632
1633         if(!parse_options(argc, argv))
1634                 return 1;
1635         
1636         make_names();
1637
1638         if(show_version) {
1639                 version();
1640                 return 0;
1641         }
1642
1643         if(show_help) {
1644                 usage(false);
1645                 return 0;
1646         }
1647
1648         if(optind >= argc) {
1649                 fprintf(stderr, "No command given.\n");
1650                 usage(true);
1651                 return 1;
1652         }
1653
1654         for(int i = 0; commands[i].command; i++) {
1655                 if(!strcasecmp(argv[optind], commands[i].command))
1656                         return commands[i].function(argc - optind, argv + optind);
1657         }
1658
1659         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1660         usage(true);
1661         return 1;
1662 }