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