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