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