Try sending SIGTERM if we cannot connect to a tincd but we know its PID.
[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         return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
742 }
743
744 static int cmd_reload(int argc, char *argv[]) {
745         if(!connect_tincd())
746                 return 1;
747
748         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
749         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
750                 fprintf(stderr, "Could not reload configuration.\n");
751                 return 1;
752         }
753
754         return 0;
755
756 }
757
758 static int cmd_dump(int argc, char *argv[]) {
759         if(argc != 2) {
760                 fprintf(stderr, "Invalid number of arguments.\n");
761                 usage(true);
762                 return 1;
763         }
764
765         if(!connect_tincd())
766                 return 1;
767
768         bool do_graph = false;
769
770         if(!strcasecmp(argv[1], "nodes"))
771                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
772         else if(!strcasecmp(argv[1], "edges"))
773                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
774         else if(!strcasecmp(argv[1], "subnets"))
775                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
776         else if(!strcasecmp(argv[1], "connections"))
777                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
778         else if(!strcasecmp(argv[1], "graph")) {
779                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
780                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
781                 do_graph = true;
782         } else {
783                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
784                 usage(true);
785                 return 1;
786         }
787
788         if(do_graph)
789                 printf("digraph {\n");
790
791         while(recvline(fd, line, sizeof line)) {
792                 char node1[4096], node2[4096];
793                 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
794                 if(n == 2) {
795                         if(do_graph && req == REQ_DUMP_NODES)
796                                 continue;
797                         else {
798                                 if(do_graph)
799                                         printf("}\n");
800                                 return 0;
801                         }
802                 }
803                 if(n < 2)
804                         break;
805
806                 if(!do_graph)
807                         printf("%s\n", line + 5);
808                 else {
809                         if(req == REQ_DUMP_NODES)
810                                 printf(" %s [label = \"%s\"];\n", node1, node1);
811                         else
812                                 printf(" %s -> %s;\n", node1, node2);
813                 }
814         }
815
816         fprintf(stderr, "Error receiving dump.\n");
817         return 1;
818 }
819
820 static int cmd_purge(int argc, char *argv[]) {
821         if(!connect_tincd())
822                 return 1;
823
824         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
825         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
826                 fprintf(stderr, "Could not purge old information.\n");
827                 return 1;
828         }
829
830         return 0;
831 }
832
833 static int cmd_debug(int argc, char *argv[]) {
834         if(argc != 2) {
835                 fprintf(stderr, "Invalid number of arguments.\n");
836                 return 1;
837         }
838
839         if(!connect_tincd())
840                 return 1;
841
842         int debuglevel = atoi(argv[1]);
843         int origlevel;
844
845         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
846         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
847                 fprintf(stderr, "Could not set debug level.\n");
848                 return 1;
849         }
850
851         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
852         return 0;
853 }
854
855 static int cmd_retry(int argc, char *argv[]) {
856         if(!connect_tincd())
857                 return 1;
858
859         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
860         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
861                 fprintf(stderr, "Could not retry outgoing connections.\n");
862                 return 1;
863         }
864
865         return 0;
866 }
867
868 static int cmd_connect(int argc, char *argv[]) {
869         if(argc != 2) {
870                 fprintf(stderr, "Invalid number of arguments.\n");
871                 return 1;
872         }
873
874         if(!check_id(argv[2])) {
875                 fprintf(stderr, "Invalid name for node.\n");
876                 return 1;
877         }
878
879         if(!connect_tincd())
880                 return 1;
881
882         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
883         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
884                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
885                 return 1;
886         }
887
888         return 0;
889 }
890
891 static int cmd_disconnect(int argc, char *argv[]) {
892         if(argc != 2) {
893                 fprintf(stderr, "Invalid number of arguments.\n");
894                 return 1;
895         }
896
897         if(!check_id(argv[2])) {
898                 fprintf(stderr, "Invalid name for node.\n");
899                 return 1;
900         }
901
902         if(!connect_tincd())
903                 return 1;
904
905         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
906         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
907                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
908                 return 1;
909         }
910
911         return 0;
912 }
913
914 static int cmd_top(int argc, char *argv[]) {
915 #ifdef HAVE_CURSES
916         if(!connect_tincd())
917                 return 1;
918
919         top(fd);
920         return 0;
921 #else
922         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
923         return 1;
924 #endif
925 }
926
927 static int cmd_pcap(int argc, char *argv[]) {
928         if(!connect_tincd())
929                 return 1;
930
931         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
932         return 0;
933 }
934
935 static int cmd_log(int argc, char *argv[]) {
936         if(!connect_tincd())
937                 return 1;
938
939         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
940         return 0;
941 }
942
943 static int cmd_pid(int argc, char *argv[]) {
944         if(!connect_tincd())
945                 return 1;
946
947         printf("%d\n", pid);
948         return 0;
949 }
950
951 static int rstrip(char *value) {
952         int len = strlen(value);
953         while(len && strchr("\t\r\n ", value[len - 1]))
954                 value[--len] = 0;
955         return len;
956 }
957
958 static char *get_my_name() {
959         FILE *f = fopen(tinc_conf, "r");
960         if(!f) {
961                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
962                 return NULL;
963         }
964
965         char buf[4096];
966         char *value;
967         while(fgets(buf, sizeof buf, f)) {
968                 int len = strcspn(buf, "\t =");
969                 value = buf + len;
970                 value += strspn(value, "\t ");
971                 if(*value == '=') {
972                         value++;
973                         value += strspn(value, "\t ");
974                 }
975                 if(!rstrip(value))
976                         continue;
977                 buf[len] = 0;
978                 if(strcasecmp(buf, "Name"))
979                         continue;
980                 if(*value) {
981                         fclose(f);
982                         return strdup(value);
983                 }
984         }
985
986         fclose(f);
987         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
988         return NULL;
989 }
990
991 #define VAR_SERVER 1    /* Should be in tinc.conf */
992 #define VAR_HOST 2      /* Can be in host config file */
993 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
994 #define VAR_OBSOLETE 8  /* Should not be used anymore */
995
996 static struct {
997         const char *name;
998         int type;
999 } const variables[] = {
1000         /* Server configuration */
1001         {"AddressFamily", VAR_SERVER},
1002         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1003         {"BindToInterface", VAR_SERVER},
1004         {"Broadcast", VAR_SERVER},
1005         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1006         {"DecrementTTL", VAR_SERVER},
1007         {"Device", VAR_SERVER},
1008         {"DeviceType", VAR_SERVER},
1009         {"DirectOnly", VAR_SERVER},
1010         {"ECDSAPrivateKeyFile", VAR_SERVER},
1011         {"ExperimentalProtocol", VAR_SERVER},
1012         {"Forwarding", VAR_SERVER},
1013         {"GraphDumpFile", VAR_SERVER},
1014         {"Hostnames", VAR_SERVER},
1015         {"IffOneQueue", VAR_SERVER},
1016         {"Interface", VAR_SERVER},
1017         {"KeyExpire", VAR_SERVER},
1018         {"LocalDiscovery", VAR_SERVER},
1019         {"MACExpire", VAR_SERVER},
1020         {"MaxTimeout", VAR_SERVER},
1021         {"Mode", VAR_SERVER},
1022         {"Name", VAR_SERVER},
1023         {"PingInterval", VAR_SERVER},
1024         {"PingTimeout", VAR_SERVER},
1025         {"PriorityInheritance", VAR_SERVER},
1026         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1027         {"PrivateKeyFile", VAR_SERVER},
1028         {"ProcessPriority", VAR_SERVER},
1029         {"ReplayWindow", VAR_SERVER},
1030         {"StrictSubnets", VAR_SERVER},
1031         {"TunnelServer", VAR_SERVER},
1032         {"UDPRcvBuf", VAR_SERVER},
1033         {"UDPSndBuf", VAR_SERVER},
1034         /* Host configuration */
1035         {"Address", VAR_HOST | VAR_MULTIPLE},
1036         {"Cipher", VAR_SERVER | VAR_HOST},
1037         {"ClampMSS", VAR_SERVER | VAR_HOST},
1038         {"Compression", VAR_SERVER | VAR_HOST},
1039         {"Digest", VAR_SERVER | VAR_HOST},
1040         {"IndirectData", VAR_SERVER | VAR_HOST},
1041         {"MACLength", VAR_SERVER | VAR_HOST},
1042         {"PMTU", VAR_SERVER | VAR_HOST},
1043         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1044         {"Port", VAR_HOST},
1045         {"PublicKey", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1046         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1047         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1048         {"TCPOnly", VAR_SERVER | VAR_HOST},
1049         {NULL, 0}
1050 };
1051
1052 static int cmd_config(int argc, char *argv[]) {
1053         if(argc < 2) {
1054                 fprintf(stderr, "Invalid number of arguments.\n");
1055                 return 1;
1056         }
1057
1058         int action = 0;
1059         if(!strcasecmp(argv[1], "add")) {
1060                 argv++, argc--, action = 1;
1061         } else if(!strcasecmp(argv[1], "del")) {
1062                 argv++, argc--, action = -1;
1063         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1064                 argv++, argc--, action = 0;
1065         }
1066
1067         if(argc < 2) {
1068                 fprintf(stderr, "Invalid number of arguments.\n");
1069                 return 1;
1070         }
1071
1072         // Concatenate the rest of the command line
1073         strncpy(line, argv[1], sizeof line - 1);
1074         for(int i = 2; i < argc; i++) {
1075                 strncat(line, " ", sizeof line - 1 - strlen(line));
1076                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1077         }
1078
1079         // Liberal parsing into node name, variable name and value.
1080         char *node = NULL;
1081         char *variable;
1082         char *value;
1083         int len;
1084
1085         len = strcspn(line, "\t =");
1086         value = line + len;
1087         value += strspn(value, "\t ");
1088         if(*value == '=') {
1089                 value++;
1090                 value += strspn(value, "\t ");
1091         }
1092         line[len] = '\0';
1093         variable = strchr(line, '.');
1094         if(variable) {
1095                 node = line;
1096                 *variable++ = 0;
1097         } else {
1098                 variable = line;
1099         }
1100
1101         if(!*variable) {
1102                 fprintf(stderr, "No variable given.\n");
1103                 return 1;
1104         }
1105
1106         if(action >= 0 && !*value) {
1107                 fprintf(stderr, "No value for variable given.\n");
1108                 return 1;
1109         }
1110
1111         /* Some simple checks. */
1112         bool found = false;
1113
1114         for(int i = 0; variables[i].name; i++) {
1115                 if(strcasecmp(variables[i].name, variable))
1116                         continue;
1117
1118                 found = true;
1119                 variable = (char *)variables[i].name;
1120
1121                 /* Discourage use of obsolete variables. */
1122
1123                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1124                         if(force) {
1125                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1126                         } else {
1127                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1128                                 return 1;
1129                         }
1130                 }
1131
1132                 /* Don't put server variables in host config files */
1133
1134                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1135                         if(force) {
1136                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1137                         } else {
1138                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1139                                 return 1;
1140                         }
1141                 }
1142
1143                 /* Should this go into our own host config file? */
1144
1145                 if(!node && !(variables[i].type & VAR_SERVER)) {
1146                         node = get_my_name();
1147                         if(!node)
1148                                 return 1;
1149                 }
1150
1151                 break;
1152         }
1153
1154         if(node && !check_id(node)) {
1155                 fprintf(stderr, "Invalid name for node.\n");
1156                 return 1;
1157         }
1158
1159         if(!found && action >= 0) {
1160                 if(force) {
1161                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1162                 } else {
1163                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1164                         return 1;
1165                 }
1166         }
1167
1168         // Open the right configuration file.
1169         char *filename;
1170         if(node)
1171                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1172         else
1173                 filename = tinc_conf;
1174
1175         FILE *f = fopen(filename, "r");
1176         if(!f) {
1177                 if(action < 0 || errno != ENOENT) {
1178                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1179                         return 1;
1180                 }
1181
1182                 // If it doesn't exist, create it.
1183                 f = fopen(filename, "a+");
1184                 if(!f) {
1185                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1186                         return 1;
1187                 } else {
1188                         fprintf(stderr, "Created configuration file %s.\n", filename);
1189                 }
1190         }
1191
1192         char *tmpfile;
1193         xasprintf(&tmpfile, "%s.config.tmp", filename);
1194         FILE *tf = fopen(tmpfile, "w");
1195         if(!tf) {
1196                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1197                 return 1;
1198         }
1199
1200         // Copy the file, making modifications on the fly.
1201         char buf1[4096];
1202         char buf2[4096];
1203         bool set = false;
1204         bool removed = false;
1205
1206         while(fgets(buf1, sizeof buf1, f)) {
1207                 buf1[sizeof buf1 - 1] = 0;
1208                 strncpy(buf2, buf1, sizeof buf2);
1209
1210                 // Parse line in a simple way
1211                 char *bvalue;
1212                 int len;
1213
1214                 len = strcspn(buf2, "\t =");
1215                 bvalue = buf2 + len;
1216                 bvalue += strspn(bvalue, "\t ");
1217                 if(*bvalue == '=') {
1218                         bvalue++;
1219                         bvalue += strspn(bvalue, "\t ");
1220                 }
1221                 rstrip(bvalue);
1222                 buf2[len] = '\0';
1223
1224                 // Did it match?
1225                 if(!strcasecmp(buf2, variable)) {
1226                         // Del
1227                         if(action < 0) {
1228                                 if(!*value || !strcasecmp(bvalue, value)) {
1229                                         removed = true;
1230                                         continue;
1231                                 }
1232                         // Set
1233                         } else if(action == 0) {
1234                                 // Already set? Delete the rest...
1235                                 if(set)
1236                                         continue;
1237                                 // Otherwise, replace.
1238                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1239                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1240                                         return 1;
1241                                 }
1242                                 set = true;
1243                                 continue;
1244                         }
1245                 }
1246
1247                 // Copy original line...
1248                 if(fputs(buf1, tf) < 0) {
1249                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1250                         return 1;
1251                 }
1252
1253                 // Add newline if it is missing...
1254                 if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1255                         if(fputc('\n', tf) < 0) {
1256                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1257                                 return 1;
1258                         }
1259                 }
1260         }
1261
1262         // Make sure we read everything...
1263         if(ferror(f) || !feof(f)) {
1264                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1265                 return 1;
1266         }
1267
1268         if(fclose(f)) {
1269                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1270                 return 1;
1271         }
1272
1273         // Add new variable if necessary.
1274         if(action > 0 || (action == 0 && !set)) {
1275                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1276                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1277                         return 1;
1278                 }
1279         }
1280
1281         // Make sure we wrote everything...
1282         if(fclose(tf)) {
1283                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1284                 return 1;
1285         }
1286
1287         // Could we find what we had to remove?
1288         if(action < 0 && !removed) {
1289                 remove(tmpfile);
1290                 fprintf(stderr, "No configuration variables deleted.\n");
1291                 return *value;
1292         }
1293
1294         // Replace the configuration file with the new one
1295 #ifdef HAVE_MINGW
1296         if(remove(filename)) {
1297                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1298                 return 1;
1299         }
1300 #endif
1301         if(rename(tmpfile, filename)) {
1302                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1303                 return 1;
1304         }
1305
1306         // Silently try notifying a running tincd of changes.
1307         fclose(stderr);
1308
1309         if(connect_tincd())
1310                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1311
1312         return 0;
1313 }
1314
1315 bool check_id(const char *name) {
1316         for(int i = 0; i < strlen(name); i++) {
1317                 if(!isalnum(name[i]) && name[i] != '_')
1318                         return false;
1319         }
1320
1321         return true;
1322 }
1323
1324 static int cmd_init(int argc, char *argv[]) {
1325         if(!access(tinc_conf, F_OK)) {
1326                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1327                 return 1;
1328         }
1329
1330         if(argc < 2) {
1331                 if(isatty(0) && isatty(1)) {
1332                         char buf[1024];
1333                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1334                         fflush(stdout);
1335                         if(!fgets(buf, sizeof buf, stdin)) {
1336                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1337                                 return 1;
1338                         }
1339                         int len = rstrip(buf);
1340                         if(!len) {
1341                                 fprintf(stderr, "No name given!\n");
1342                                 return 1;
1343                         }
1344                         name = strdup(buf);
1345                 } else {
1346                         fprintf(stderr, "No Name given!\n");
1347                         return 1;
1348                 }
1349         } else {
1350                 name = strdup(argv[1]);
1351                 if(!*name) {
1352                         fprintf(stderr, "No Name given!\n");
1353                         return 1;
1354                 }
1355         }
1356
1357         if(!check_id(name)) {
1358                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1359                 return 1;
1360         }
1361
1362         if(mkdir(confdir, 0755) && errno != EEXIST) {
1363                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1364                 return 1;
1365         }
1366
1367         if(mkdir(confbase, 0755) && errno != EEXIST) {
1368                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1369                 return 1;
1370         }
1371
1372         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1373                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1374                 return 1;
1375         }
1376
1377         FILE *f = fopen(tinc_conf, "w");
1378         if(!f) {
1379                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1380                 return 1;
1381         }
1382
1383         fprintf(f, "Name = %s\n", name);
1384         fclose(f);
1385
1386         fclose(stdin);
1387         if(!rsa_keygen(2048) || !ecdsa_keygen())
1388                 return 1;
1389
1390 #ifndef HAVE_MINGW
1391         char *filename;
1392         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1393         if(access(filename, F_OK)) {
1394                 FILE *f = fopen(filename, "w");
1395                 if(!f) {
1396                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1397                         return 1;
1398                 }
1399                 fchmod(fileno(f), 0755);
1400                 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");
1401                 fclose(f);
1402         }
1403 #endif
1404
1405         return 0;
1406
1407 }
1408
1409 static int cmd_generate_keys(int argc, char *argv[]) {
1410         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1411 }
1412
1413 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1414         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1415 }
1416
1417 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1418         return !ecdsa_keygen();
1419 }
1420
1421 static int cmd_help(int argc, char *argv[]) {
1422         usage(false);
1423         return 0;
1424 }
1425
1426 static int cmd_version(int argc, char *argv[]) {
1427         version();
1428         return 0;
1429 }
1430
1431 static int cmd_info(int argc, char *argv[]) {
1432         if(argc != 2) {
1433                 fprintf(stderr, "Invalid number of arguments.\n");
1434                 return 1;
1435         }
1436
1437         if(!connect_tincd())
1438                 return 1;
1439
1440         return info(fd, argv[1]);
1441 }
1442
1443 static const char *conffiles[] = {
1444         "tinc.conf",
1445         "tinc-up",
1446         "tinc-down",
1447         "subnet-up",
1448         "subnet-down",
1449         "host-up",
1450         "host-down",
1451         NULL,
1452 };
1453
1454 static int cmd_edit(int argc, char *argv[]) {
1455         if(argc != 2) {
1456                 fprintf(stderr, "Invalid number of arguments.\n");
1457                 return 1;
1458         }
1459
1460         char *filename = NULL;
1461
1462         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1463                 for(int i = 0; conffiles[i]; i++) {
1464                         if(!strcmp(argv[1], conffiles[i])) {
1465                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1466                                 break;
1467                         }
1468                 }
1469         } else {
1470                 argv[1] += 6;
1471         }
1472
1473         if(!filename) {
1474                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1475                 char *dash = strchr(argv[1], '-');
1476                 if(dash) {
1477                         *dash++ = 0;
1478                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1479                                 fprintf(stderr, "Invalid configuration filename.\n");
1480                                 return 1;
1481                         }
1482                 }
1483         }
1484
1485         char *command;
1486 #ifndef HAVE_MINGW
1487         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1488 #else
1489         xasprintf(&command, "edit \"%s\"", filename);
1490 #endif
1491         int result = system(command);
1492         if(result)
1493                 return result;
1494
1495         // Silently try notifying a running tincd of changes.
1496         fclose(stderr);
1497
1498         if(connect_tincd())
1499                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1500
1501         return 0;
1502 }
1503
1504 static int export(const char *name, FILE *out) {
1505         char *filename;
1506         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1507         FILE *in = fopen(filename, "r");
1508         if(!in) {
1509                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1510                 return 1;
1511         }
1512
1513         fprintf(out, "Name = %s\n", name);
1514         char buf[4096];
1515         while(fgets(buf, sizeof buf, in)) {
1516                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1517                         fputs(buf, out);
1518         }
1519
1520         if(ferror(in)) {
1521                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1522                 return 1;
1523         }
1524
1525         fclose(in);
1526         return 0;
1527 }
1528
1529 static int cmd_export(int argc, char *argv[]) {
1530         char *name = get_my_name();
1531         if(!name)
1532                 return 1;
1533
1534         return export(name, stdout);
1535 }
1536
1537 static int cmd_export_all(int argc, char *argv[]) {
1538         DIR *dir = opendir(hosts_dir);
1539         if(!dir) {
1540                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1541                 return 1;
1542         }
1543
1544         bool first = true;
1545         int result = 0;
1546         struct dirent *ent;
1547
1548         while((ent = readdir(dir))) {
1549                 if(!check_id(ent->d_name))
1550                         continue;
1551
1552                 if(first)
1553                         first = false;
1554                 else
1555                         printf("#---------------------------------------------------------------#\n");
1556
1557                 result |= export(ent->d_name, stdout);
1558         }
1559
1560         closedir(dir);
1561         return result;
1562 }
1563
1564 static int cmd_import(int argc, char *argv[]) {
1565         FILE *in = stdin;
1566         FILE *out = NULL;
1567
1568         char buf[4096];
1569         char name[4096];
1570         char *filename;
1571         int count = 0;
1572         bool firstline = true;
1573
1574         while(fgets(buf, sizeof buf, in)) {
1575                 if(sscanf(buf, "Name = %s", name) == 1) {
1576                         if(!check_id(name)) {
1577                                 fprintf(stderr, "Invalid Name in input!\n");
1578                                 return 1;
1579                         }
1580
1581                         if(out)
1582                                 fclose(out);
1583
1584                         free(filename);
1585                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1586
1587                         if(!force && !access(filename, F_OK)) {
1588                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1589                                 out = NULL;
1590                                 continue;
1591                         }
1592
1593                         out = fopen(filename, "w");
1594                         if(!out) {
1595                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1596                                 return 1;
1597                         }
1598
1599                         count++;
1600                         firstline = false;
1601                         continue;
1602                 } else if(firstline) {
1603                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1604                         firstline = false;
1605                 }
1606
1607
1608                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1609                         continue;
1610
1611                 if(out) {
1612                         if(fputs(buf, out) < 0) {
1613                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1614                                 return 1;
1615                         }
1616                 }
1617         }
1618
1619         if(out)
1620                 fclose(out);
1621
1622         if(count) {
1623                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1624                 return 0;
1625         } else {
1626                 fprintf(stderr, "No host configuration files imported.\n");
1627                 return 1;
1628         }
1629 }
1630
1631 static const struct {
1632         const char *command;
1633         int (*function)(int argc, char *argv[]);
1634 } commands[] = {
1635         {"start", cmd_start},
1636         {"stop", cmd_stop},
1637         {"restart", cmd_restart},
1638         {"reload", cmd_reload},
1639         {"dump", cmd_dump},
1640         {"purge", cmd_purge},
1641         {"debug", cmd_debug},
1642         {"retry", cmd_retry},
1643         {"connect", cmd_connect},
1644         {"disconnect", cmd_disconnect},
1645         {"top", cmd_top},
1646         {"pcap", cmd_pcap},
1647         {"log", cmd_log},
1648         {"pid", cmd_pid},
1649         {"config", cmd_config},
1650         {"init", cmd_init},
1651         {"generate-keys", cmd_generate_keys},
1652         {"generate-rsa-keys", cmd_generate_rsa_keys},
1653         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1654         {"help", cmd_help},
1655         {"version", cmd_version},
1656         {"info", cmd_info},
1657         {"edit", cmd_edit},
1658         {"export", cmd_export},
1659         {"export-all", cmd_export_all},
1660         {"import", cmd_import},
1661         {NULL, NULL},
1662 };
1663
1664 int main(int argc, char *argv[]) {
1665         program_name = argv[0];
1666
1667         if(!parse_options(argc, argv))
1668                 return 1;
1669         
1670         make_names();
1671
1672         if(show_version) {
1673                 version();
1674                 return 0;
1675         }
1676
1677         if(show_help) {
1678                 usage(false);
1679                 return 0;
1680         }
1681
1682         if(optind >= argc) {
1683                 fprintf(stderr, "No command given.\n");
1684                 usage(true);
1685                 return 1;
1686         }
1687
1688         for(int i = 0; commands[i].command; i++) {
1689                 if(!strcasecmp(argv[optind], commands[i].command))
1690                         return commands[i].function(argc - optind, argv + optind);
1691         }
1692
1693         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1694         usage(true);
1695         return 1;
1696 }