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