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