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