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