Add an easy way to edit a configuration file.
[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(!check_id(argv[2])) {
836                 fprintf(stderr, "Invalid name for node.\n");
837                 return 1;
838         }
839
840         if(!connect_tincd())
841                 return 1;
842
843         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
844         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
845                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
846                 return 1;
847         }
848
849         return 0;
850 }
851
852 static int cmd_disconnect(int argc, char *argv[]) {
853         if(argc != 2) {
854                 fprintf(stderr, "Invalid number of arguments.\n");
855                 return 1;
856         }
857
858         if(!check_id(argv[2])) {
859                 fprintf(stderr, "Invalid name for node.\n");
860                 return 1;
861         }
862
863         if(!connect_tincd())
864                 return 1;
865
866         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
867         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
868                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
869                 return 1;
870         }
871
872         return 0;
873 }
874
875 static int cmd_top(int argc, char *argv[]) {
876 #ifdef HAVE_CURSES
877         if(!connect_tincd())
878                 return 1;
879
880         top(fd);
881         return 0;
882 #else
883         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
884         return 1;
885 #endif
886 }
887
888 static int cmd_pcap(int argc, char *argv[]) {
889         if(!connect_tincd())
890                 return 1;
891
892         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
893         return 0;
894 }
895
896 static int cmd_log(int argc, char *argv[]) {
897         if(!connect_tincd())
898                 return 1;
899
900         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
901         return 0;
902 }
903
904 static int cmd_pid(int argc, char *argv[]) {
905         if(!connect_tincd())
906                 return 1;
907
908         printf("%d\n", pid);
909         return 0;
910 }
911
912 static int rstrip(char *value) {
913         int len = strlen(value);
914         while(len && strchr("\t\r\n ", value[len - 1]))
915                 value[--len] = 0;
916         return len;
917 }
918
919 static char *get_my_name() {
920         FILE *f = fopen(tinc_conf, "r");
921         if(!f) {
922                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
923                 return NULL;
924         }
925
926         char buf[4096];
927         char *value;
928         while(fgets(buf, sizeof buf, f)) {
929                 int len = strcspn(buf, "\t =");
930                 value = buf + len;
931                 value += strspn(value, "\t ");
932                 if(*value == '=') {
933                         value++;
934                         value += strspn(value, "\t ");
935                 }
936                 if(!rstrip(value))
937                         continue;
938                 buf[len] = 0;
939                 if(strcasecmp(buf, "Name"))
940                         continue;
941                 if(*value) {
942                         fclose(f);
943                         return strdup(value);
944                 }
945         }
946
947         fclose(f);
948         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
949         return NULL;
950 }
951
952 static char *hostvariables[] = {
953         "Address",
954         "Port",
955         "PublicKey",
956         "Subnet",
957         NULL,
958 };
959
960 static int cmd_config(int argc, char *argv[]) {
961         if(argc < 2) {
962                 fprintf(stderr, "Invalid number of arguments.\n");
963                 return 1;
964         }
965
966         int action = 0;
967         if(!strcasecmp(argv[1], "add")) {
968                 argv++, argc--, action = 1;
969         } else if(!strcasecmp(argv[1], "del")) {
970                 argv++, argc--, action = -1;
971         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
972                 argv++, argc--, action = 0;
973         }
974
975         if(argc < 2) {
976                 fprintf(stderr, "Invalid number of arguments.\n");
977                 return 1;
978         }
979
980         // Concatenate the rest of the command line
981         strncpy(line, argv[1], sizeof line - 1);
982         for(int i = 2; i < argc; i++) {
983                 strncat(line, " ", sizeof line - 1 - strlen(line));
984                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
985         }
986
987         // Liberal parsing into node name, variable name and value.
988         char *node = NULL;
989         char *variable;
990         char *value;
991         int len;
992
993         len = strcspn(line, "\t =");
994         value = line + len;
995         value += strspn(value, "\t ");
996         if(*value == '=') {
997                 value++;
998                 value += strspn(value, "\t ");
999         }
1000         line[len] = '\0';
1001         variable = strchr(line, '.');
1002         if(variable) {
1003                 node = line;
1004                 *variable++ = 0;
1005         } else {
1006                 variable = line;
1007         }
1008
1009         if(!*variable) {
1010                 fprintf(stderr, "No variable given.\n");
1011                 return 1;
1012         }
1013
1014         if(action >= 0 && !*value) {
1015                 fprintf(stderr, "No value for variable given.\n");
1016                 return 1;
1017         }
1018
1019         // Should this go into our own host config file?
1020         if(!node) {
1021                 for(int i = 0; hostvariables[i]; i++) {
1022                         if(!strcasecmp(hostvariables[i], variable)) {
1023                                 node = get_my_name();
1024                                 if(!node)
1025                                         return 1;
1026                                 break;
1027                         }
1028                 }
1029         }
1030
1031         if(node && !check_id(node)) {
1032                 fprintf(stderr, "Invalid name for node.\n");
1033                 return 1;
1034         }
1035
1036         // Open the right configuration file.
1037         char *filename;
1038         if(node)
1039                 xasprintf(&filename, "%s/%s", hosts_dir, node);
1040         else
1041                 filename = tinc_conf;
1042
1043         FILE *f = fopen(filename, "r");
1044         if(!f) {
1045                 if(action < 0 || errno != ENOENT) {
1046                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1047                         return 1;
1048                 }
1049
1050                 // If it doesn't exist, create it.
1051                 f = fopen(filename, "a+");
1052                 if(!f) {
1053                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1054                         return 1;
1055                 } else {
1056                         fprintf(stderr, "Created configuration file %s.\n", filename);
1057                 }
1058         }
1059
1060         char *tmpfile;
1061         xasprintf(&tmpfile, "%s.config.tmp", filename);
1062         FILE *tf = fopen(tmpfile, "w");
1063         if(!tf) {
1064                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1065                 return 1;
1066         }
1067
1068         // Copy the file, making modifications on the fly.
1069         char buf1[4096];
1070         char buf2[4096];
1071         bool set = false;
1072         bool removed = false;
1073
1074         while(fgets(buf1, sizeof buf1, f)) {
1075                 buf1[sizeof buf1 - 1] = 0;
1076                 strcpy(buf2, buf1);
1077
1078                 // Parse line in a simple way
1079                 char *bvalue;
1080                 int len;
1081
1082                 len = strcspn(buf2, "\t =");
1083                 bvalue = buf2 + len;
1084                 bvalue += strspn(bvalue, "\t ");
1085                 if(*bvalue == '=') {
1086                         bvalue++;
1087                         bvalue += strspn(bvalue, "\t ");
1088                 }
1089                 rstrip(bvalue);
1090                 buf2[len] = '\0';
1091
1092                 // Did it match?
1093                 if(!strcasecmp(buf2, variable)) {
1094                         // Del
1095                         if(action < 0) {
1096                                 if(!*value || !strcasecmp(bvalue, value)) {
1097                                         removed = true;
1098                                         continue;
1099                                 }
1100                         // Set
1101                         } else if(action == 0) {
1102                                 // Already set? Delete the rest...
1103                                 if(set)
1104                                         continue;
1105                                 // Otherwise, replace.
1106                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1107                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1108                                         return 1;
1109                                 }
1110                                 set = true;
1111                                 continue;
1112                         }
1113                 }
1114
1115                 // Copy original line...
1116                 if(fputs(buf1, tf) < 0) {
1117                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1118                         return 1;
1119                 }
1120         }
1121
1122         // Make sure we read everything...
1123         if(ferror(f) || !feof(f)) {
1124                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1125                 return 1;
1126         }
1127
1128         if(fclose(f)) {
1129                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1130                 return 1;
1131         }
1132
1133         // Add new variable if necessary.
1134         if(action > 0 || (action == 0 && !set)) {
1135                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1136                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1137                         return 1;
1138                 }
1139         }
1140
1141         // Make sure we wrote everything...
1142         if(fclose(tf)) {
1143                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1144                 return 1;
1145         }
1146
1147         // Could we find what we had to remove?
1148         if(action < 0 && !removed) {
1149                 remove(tmpfile);
1150                 fprintf(stderr, "No configuration variables deleted.\n");
1151                 return *value;
1152         }
1153
1154         // Replace the configuration file with the new one
1155 #ifdef HAVE_MINGW
1156         if(remove(filename)) {
1157                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1158                 return 1;
1159         }
1160 #endif
1161         if(rename(tmpfile, filename)) {
1162                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1163                 return 1;
1164         }
1165
1166         return 0;
1167 }
1168
1169 bool check_id(const char *name) {
1170         for(int i = 0; i < strlen(name); i++) {
1171                 if(!isalnum(name[i]) && name[i] != '_')
1172                         return false;
1173         }
1174
1175         return true;
1176 }
1177
1178 static int cmd_init(int argc, char *argv[]) {
1179         if(!access(tinc_conf, F_OK)) {
1180                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1181                 return 1;
1182         }
1183
1184         if(argc < 2) {
1185                 if(isatty(0) && isatty(1)) {
1186                         char buf[1024];
1187                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1188                         fflush(stdout);
1189                         if(!fgets(buf, sizeof buf, stdin)) {
1190                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1191                                 return 1;
1192                         }
1193                         int len = rstrip(buf);
1194                         if(!len) {
1195                                 fprintf(stderr, "No name given!\n");
1196                                 return 1;
1197                         }
1198                         name = strdup(buf);
1199                 } else {
1200                         fprintf(stderr, "No Name given!\n");
1201                         return 1;
1202                 }
1203         } else {
1204                 name = strdup(argv[1]);
1205                 if(!*name) {
1206                         fprintf(stderr, "No Name given!\n");
1207                         return 1;
1208                 }
1209         }
1210
1211         if(!check_id(name)) {
1212                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1213                 return 1;
1214         }
1215
1216         if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1217                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1218                 return 1;
1219         }
1220
1221         if(mkdir(confbase, 0755) && errno != EEXIST) {
1222                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1223                 return 1;
1224         }
1225
1226         char *hosts_dir = NULL;
1227         xasprintf(&hosts_dir, "%s/hosts", confbase);
1228         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1229                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1230                 return 1;
1231         }
1232
1233         FILE *f = fopen(tinc_conf, "w");
1234         if(!f) {
1235                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1236                 return 1;
1237         }
1238
1239         fprintf(f, "Name = %s\n", name);
1240         fclose(f);
1241
1242         fclose(stdin);
1243         if(!rsa_keygen(2048) || !ecdsa_keygen())
1244                 return false;
1245
1246         return true;
1247
1248 }
1249
1250 static int cmd_generate_keys(int argc, char *argv[]) {
1251         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1252 }
1253
1254 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1255         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1256 }
1257
1258 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1259         return !ecdsa_keygen();
1260 }
1261
1262 static int cmd_help(int argc, char *argv[]) {
1263         usage(false);
1264         return 0;
1265 }
1266
1267 static int cmd_version(int argc, char *argv[]) {
1268         version();
1269         return 0;
1270 }
1271
1272 static const char *conffiles[] = {
1273         "tinc.conf",
1274         "tinc-up",
1275         "tinc-down",
1276         "subnet-up",
1277         "subnet-down",
1278         "host-up",
1279         "host-down",
1280         NULL,
1281 };
1282
1283 static int cmd_edit(int argc, char *argv[]) {
1284         if(argc != 2) {
1285                 fprintf(stderr, "Invalid number of arguments.\n");
1286                 return 1;
1287         }
1288
1289         char *filename = NULL;
1290
1291         if(strncmp(argv[1], "hosts/", 6)) {
1292                 for(int i = 0; conffiles[i]; i++) {
1293                         if(!strcmp(argv[1], conffiles[i])) {
1294                                 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1295                                 break;
1296                         }
1297                 }
1298         } else {
1299                 argv[1] += 6;
1300         }
1301
1302         if(!filename) {
1303                 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1304                 char *dash = strchr(argv[1], '-');
1305                 if(dash) {
1306                         *dash++ = 0;
1307                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1308                                 fprintf(stderr, "Invalid configuration filename.\n");
1309                                 return 1;
1310                         }
1311                 }
1312         }
1313
1314 #ifndef HAVE_MINGW
1315         char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1316 #else
1317         char *editor = "edit"
1318 #endif
1319
1320         char *command;
1321         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1322         return system(command);
1323 }
1324
1325 static const struct {
1326         const char *command;
1327         int (*function)(int argc, char *argv[]);
1328 } commands[] = {
1329         {"start", cmd_start},
1330         {"stop", cmd_stop},
1331         {"restart", cmd_restart},
1332         {"reload", cmd_reload},
1333         {"dump", cmd_dump},
1334         {"purge", cmd_purge},
1335         {"debug", cmd_debug},
1336         {"retry", cmd_retry},
1337         {"connect", cmd_connect},
1338         {"disconnect", cmd_disconnect},
1339         {"top", cmd_top},
1340         {"pcap", cmd_pcap},
1341         {"log", cmd_log},
1342         {"pid", cmd_pid},
1343         {"config", cmd_config},
1344         {"init", cmd_init},
1345         {"generate-keys", cmd_generate_keys},
1346         {"generate-rsa-keys", cmd_generate_rsa_keys},
1347         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1348         {"help", cmd_help},
1349         {"version", cmd_version},
1350         {"edit", cmd_edit},
1351         {NULL, NULL},
1352 };
1353
1354 int main(int argc, char *argv[]) {
1355         program_name = argv[0];
1356
1357         if(!parse_options(argc, argv))
1358                 return 1;
1359         
1360         make_names();
1361
1362         if(show_version) {
1363                 version();
1364                 return 0;
1365         }
1366
1367         if(show_help) {
1368                 usage(false);
1369                 return 0;
1370         }
1371
1372         if(optind >= argc) {
1373                 fprintf(stderr, "No command given.\n");
1374                 usage(true);
1375                 return 1;
1376         }
1377
1378         for(int i = 0; commands[i].command; i++) {
1379                 if(!strcasecmp(argv[optind], commands[i].command))
1380                         return commands[i].function(argc - optind, argv + optind);
1381         }
1382
1383         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1384         usage(true);
1385         return 1;
1386 }