Fix tincctl start.
[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
659         argc += optind;
660         argv -= optind;
661         char *slash = strrchr(argv[0], '/');
662
663 #ifdef HAVE_MINGW
664         if ((c = strrchr(argv[0], '\\')) > slash)
665                 slash = c;
666 #endif
667
668         if (slash++) {
669                 c = xmalloc((slash - argv[0]) + sizeof("tincd"));
670                 sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
671         }
672         else
673                 c = "tincd";
674
675         argv[0] = c;
676
677         for(i = j = 1; argv[i]; ++i)
678                 if (i != optind && strcmp(argv[i], "--") != 0)
679                         argv[j++] = argv[i];
680
681         argv[j] = NULL;
682         execvp(c, argv);
683         fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
684         return 1;
685 }
686
687 static int cmd_stop(int argc, char *argv[]) {
688 #ifndef HAVE_MINGW
689         if(!connect_tincd())
690                 return 1;
691
692         sendline(fd, "%d %d", CONTROL, REQ_STOP);
693         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
694                 fprintf(stderr, "Could not stop tinc daemon.\n");
695                 return 1;
696         }
697 #else
698         if(!remove_service())
699                 return 1;
700 #endif
701         return 0;
702 }
703
704 static int cmd_restart(int argc, char *argv[]) {
705         return cmd_stop(argc, argv) ?: cmd_start(argc, argv);
706 }
707
708 static int cmd_reload(int argc, char *argv[]) {
709         if(!connect_tincd())
710                 return 1;
711
712         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
713         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
714                 fprintf(stderr, "Could not reload configuration.\n");
715                 return 1;
716         }
717
718         return 0;
719
720 }
721
722 static int cmd_dump(int argc, char *argv[]) {
723         if(argc != 2) {
724                 fprintf(stderr, "Invalid number of arguments.\n");
725                 usage(true);
726                 return 1;
727         }
728
729         bool do_graph = false;
730
731         if(!strcasecmp(argv[1], "nodes"))
732                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
733         else if(!strcasecmp(argv[1], "edges"))
734                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
735         else if(!strcasecmp(argv[1], "subnets"))
736                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
737         else if(!strcasecmp(argv[1], "connections"))
738                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
739         else if(!strcasecmp(argv[1], "graph")) {
740                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
741                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
742                 do_graph = true;
743         } else {
744                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
745                 usage(true);
746                 return 1;
747         }
748
749         if(!connect_tincd())
750                 return 1;
751
752         if(do_graph)
753                 printf("digraph {\n");
754
755         while(recvline(fd, line, sizeof line)) {
756                 char node1[4096], node2[4096];
757                 int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
758                 if(n == 2) {
759                         if(do_graph && req == REQ_DUMP_NODES)
760                                 continue;
761                         else {
762                                 if(do_graph)
763                                         printf("}\n");
764                                 return 0;
765                         }
766                 }
767                 if(n < 2)
768                         break;
769
770                 if(!do_graph)
771                         printf("%s\n", line + 5);
772                 else {
773                         if(req == REQ_DUMP_NODES)
774                                 printf(" %s [label = \"%s\"];\n", node1, node1);
775                         else
776                                 printf(" %s -> %s;\n", node1, node2);
777                 }
778         }
779
780         fprintf(stderr, "Error receiving dump.\n");
781         return 1;
782 }
783
784 static int cmd_purge(int argc, char *argv[]) {
785         if(!connect_tincd())
786                 return 1;
787
788         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
789         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
790                 fprintf(stderr, "Could not purge old information.\n");
791                 return 1;
792         }
793
794         return 0;
795 }
796
797 static int cmd_debug(int argc, char *argv[]) {
798         if(argc != 2) {
799                 fprintf(stderr, "Invalid number of arguments.\n");
800                 return 1;
801         }
802
803         if(!connect_tincd())
804                 return 1;
805
806         int debuglevel = atoi(argv[1]);
807         int origlevel;
808
809         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
810         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
811                 fprintf(stderr, "Could not set debug level.\n");
812                 return 1;
813         }
814
815         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
816         return 0;
817 }
818
819 static int cmd_retry(int argc, char *argv[]) {
820         if(!connect_tincd())
821                 return 1;
822
823         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
824         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
825                 fprintf(stderr, "Could not retry outgoing connections.\n");
826                 return 1;
827         }
828
829         return 0;
830 }
831
832 static int cmd_connect(int argc, char *argv[]) {
833         if(argc != 2) {
834                 fprintf(stderr, "Invalid number of arguments.\n");
835                 return 1;
836         }
837
838         if(!check_id(argv[2])) {
839                 fprintf(stderr, "Invalid name for node.\n");
840                 return 1;
841         }
842
843         if(!connect_tincd())
844                 return 1;
845
846         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
847         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
848                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
849                 return 1;
850         }
851
852         return 0;
853 }
854
855 static int cmd_disconnect(int argc, char *argv[]) {
856         if(argc != 2) {
857                 fprintf(stderr, "Invalid number of arguments.\n");
858                 return 1;
859         }
860
861         if(!check_id(argv[2])) {
862                 fprintf(stderr, "Invalid name for node.\n");
863                 return 1;
864         }
865
866         if(!connect_tincd())
867                 return 1;
868
869         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
870         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
871                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
872                 return 1;
873         }
874
875         return 0;
876 }
877
878 static int cmd_top(int argc, char *argv[]) {
879 #ifdef HAVE_CURSES
880         if(!connect_tincd())
881                 return 1;
882
883         top(fd);
884         return 0;
885 #else
886         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
887         return 1;
888 #endif
889 }
890
891 static int cmd_pcap(int argc, char *argv[]) {
892         if(!connect_tincd())
893                 return 1;
894
895         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
896         return 0;
897 }
898
899 static int cmd_log(int argc, char *argv[]) {
900         if(!connect_tincd())
901                 return 1;
902
903         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
904         return 0;
905 }
906
907 static int cmd_pid(int argc, char *argv[]) {
908         if(!connect_tincd())
909                 return 1;
910
911         printf("%d\n", pid);
912         return 0;
913 }
914
915 static int rstrip(char *value) {
916         int len = strlen(value);
917         while(len && strchr("\t\r\n ", value[len - 1]))
918                 value[--len] = 0;
919         return len;
920 }
921
922 static char *get_my_name() {
923         FILE *f = fopen(tinc_conf, "r");
924         if(!f) {
925                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
926                 return NULL;
927         }
928
929         char buf[4096];
930         char *value;
931         while(fgets(buf, sizeof buf, f)) {
932                 int len = strcspn(buf, "\t =");
933                 value = buf + len;
934                 value += strspn(value, "\t ");
935                 if(*value == '=') {
936                         value++;
937                         value += strspn(value, "\t ");
938                 }
939                 if(!rstrip(value))
940                         continue;
941                 buf[len] = 0;
942                 if(strcasecmp(buf, "Name"))
943                         continue;
944                 if(*value) {
945                         fclose(f);
946                         return strdup(value);
947                 }
948         }
949
950         fclose(f);
951         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
952         return NULL;
953 }
954
955 static char *hostvariables[] = {
956         "Address",
957         "Port",
958         "PublicKey",
959         "Subnet",
960         NULL,
961 };
962
963 static int cmd_config(int argc, char *argv[]) {
964         if(argc < 2) {
965                 fprintf(stderr, "Invalid number of arguments.\n");
966                 return 1;
967         }
968
969         int action = 0;
970         if(!strcasecmp(argv[1], "add")) {
971                 argv++, argc--, action = 1;
972         } else if(!strcasecmp(argv[1], "del")) {
973                 argv++, argc--, action = -1;
974         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
975                 argv++, argc--, action = 0;
976         }
977
978         if(argc < 2) {
979                 fprintf(stderr, "Invalid number of arguments.\n");
980                 return 1;
981         }
982
983         // Concatenate the rest of the command line
984         strncpy(line, argv[1], sizeof line - 1);
985         for(int i = 2; i < argc; i++) {
986                 strncat(line, " ", sizeof line - 1 - strlen(line));
987                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
988         }
989
990         // Liberal parsing into node name, variable name and value.
991         char *node = NULL;
992         char *variable;
993         char *value;
994         int len;
995
996         len = strcspn(line, "\t =");
997         value = line + len;
998         value += strspn(value, "\t ");
999         if(*value == '=') {
1000                 value++;
1001                 value += strspn(value, "\t ");
1002         }
1003         line[len] = '\0';
1004         variable = strchr(line, '.');
1005         if(variable) {
1006                 node = line;
1007                 *variable++ = 0;
1008         } else {
1009                 variable = line;
1010         }
1011
1012         if(!*variable) {
1013                 fprintf(stderr, "No variable given.\n");
1014                 return 1;
1015         }
1016
1017         if(action >= 0 && !*value) {
1018                 fprintf(stderr, "No value for variable given.\n");
1019                 return 1;
1020         }
1021
1022         // Should this go into our own host config file?
1023         if(!node) {
1024                 for(int i = 0; hostvariables[i]; i++) {
1025                         if(!strcasecmp(hostvariables[i], variable)) {
1026                                 node = get_my_name();
1027                                 if(!node)
1028                                         return 1;
1029                                 break;
1030                         }
1031                 }
1032         }
1033
1034         if(node && !check_id(node)) {
1035                 fprintf(stderr, "Invalid name for node.\n");
1036                 return 1;
1037         }
1038
1039         // Open the right configuration file.
1040         char *filename;
1041         if(node)
1042                 xasprintf(&filename, "%s/%s", hosts_dir, node);
1043         else
1044                 filename = tinc_conf;
1045
1046         FILE *f = fopen(filename, "r");
1047         if(!f) {
1048                 if(action < 0 || errno != ENOENT) {
1049                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1050                         return 1;
1051                 }
1052
1053                 // If it doesn't exist, create it.
1054                 f = fopen(filename, "a+");
1055                 if(!f) {
1056                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1057                         return 1;
1058                 } else {
1059                         fprintf(stderr, "Created configuration file %s.\n", filename);
1060                 }
1061         }
1062
1063         char *tmpfile;
1064         xasprintf(&tmpfile, "%s.config.tmp", filename);
1065         FILE *tf = fopen(tmpfile, "w");
1066         if(!tf) {
1067                 fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1068                 return 1;
1069         }
1070
1071         // Copy the file, making modifications on the fly.
1072         char buf1[4096];
1073         char buf2[4096];
1074         bool set = false;
1075         bool removed = false;
1076
1077         while(fgets(buf1, sizeof buf1, f)) {
1078                 buf1[sizeof buf1 - 1] = 0;
1079                 strcpy(buf2, buf1);
1080
1081                 // Parse line in a simple way
1082                 char *bvalue;
1083                 int len;
1084
1085                 len = strcspn(buf2, "\t =");
1086                 bvalue = buf2 + len;
1087                 bvalue += strspn(bvalue, "\t ");
1088                 if(*bvalue == '=') {
1089                         bvalue++;
1090                         bvalue += strspn(bvalue, "\t ");
1091                 }
1092                 rstrip(bvalue);
1093                 buf2[len] = '\0';
1094
1095                 // Did it match?
1096                 if(!strcasecmp(buf2, variable)) {
1097                         // Del
1098                         if(action < 0) {
1099                                 if(!*value || !strcasecmp(bvalue, value)) {
1100                                         removed = true;
1101                                         continue;
1102                                 }
1103                         // Set
1104                         } else if(action == 0) {
1105                                 // Already set? Delete the rest...
1106                                 if(set)
1107                                         continue;
1108                                 // Otherwise, replace.
1109                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1110                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1111                                         return 1;
1112                                 }
1113                                 set = true;
1114                                 continue;
1115                         }
1116                 }
1117
1118                 // Copy original line...
1119                 if(fputs(buf1, tf) < 0) {
1120                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1121                         return 1;
1122                 }
1123         }
1124
1125         // Make sure we read everything...
1126         if(ferror(f) || !feof(f)) {
1127                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1128                 return 1;
1129         }
1130
1131         if(fclose(f)) {
1132                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1133                 return 1;
1134         }
1135
1136         // Add new variable if necessary.
1137         if(action > 0 || (action == 0 && !set)) {
1138                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1139                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1140                         return 1;
1141                 }
1142         }
1143
1144         // Make sure we wrote everything...
1145         if(fclose(tf)) {
1146                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1147                 return 1;
1148         }
1149
1150         // Could we find what we had to remove?
1151         if(action < 0 && !removed) {
1152                 remove(tmpfile);
1153                 fprintf(stderr, "No configuration variables deleted.\n");
1154                 return *value;
1155         }
1156
1157         // Replace the configuration file with the new one
1158 #ifdef HAVE_MINGW
1159         if(remove(filename)) {
1160                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1161                 return 1;
1162         }
1163 #endif
1164         if(rename(tmpfile, filename)) {
1165                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1166                 return 1;
1167         }
1168
1169         // Silently try notifying a running tincd of changes.
1170         fclose(stderr);
1171
1172         if(connect_tincd())
1173                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1174
1175         return 0;
1176 }
1177
1178 bool check_id(const char *name) {
1179         for(int i = 0; i < strlen(name); i++) {
1180                 if(!isalnum(name[i]) && name[i] != '_')
1181                         return false;
1182         }
1183
1184         return true;
1185 }
1186
1187 static int cmd_init(int argc, char *argv[]) {
1188         if(!access(tinc_conf, F_OK)) {
1189                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1190                 return 1;
1191         }
1192
1193         if(argc < 2) {
1194                 if(isatty(0) && isatty(1)) {
1195                         char buf[1024];
1196                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1197                         fflush(stdout);
1198                         if(!fgets(buf, sizeof buf, stdin)) {
1199                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1200                                 return 1;
1201                         }
1202                         int len = rstrip(buf);
1203                         if(!len) {
1204                                 fprintf(stderr, "No name given!\n");
1205                                 return 1;
1206                         }
1207                         name = strdup(buf);
1208                 } else {
1209                         fprintf(stderr, "No Name given!\n");
1210                         return 1;
1211                 }
1212         } else {
1213                 name = strdup(argv[1]);
1214                 if(!*name) {
1215                         fprintf(stderr, "No Name given!\n");
1216                         return 1;
1217                 }
1218         }
1219
1220         if(!check_id(name)) {
1221                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1222                 return 1;
1223         }
1224
1225         if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
1226                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1227                 return 1;
1228         }
1229
1230         if(mkdir(confbase, 0755) && errno != EEXIST) {
1231                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1232                 return 1;
1233         }
1234
1235         char *hosts_dir = NULL;
1236         xasprintf(&hosts_dir, "%s/hosts", confbase);
1237         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1238                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1239                 return 1;
1240         }
1241
1242         FILE *f = fopen(tinc_conf, "w");
1243         if(!f) {
1244                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1245                 return 1;
1246         }
1247
1248         fprintf(f, "Name = %s\n", name);
1249         fclose(f);
1250
1251         fclose(stdin);
1252         if(!rsa_keygen(2048) || !ecdsa_keygen())
1253                 return false;
1254
1255         return true;
1256
1257 }
1258
1259 static int cmd_generate_keys(int argc, char *argv[]) {
1260         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048) && ecdsa_keygen());
1261 }
1262
1263 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1264         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048);
1265 }
1266
1267 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1268         return !ecdsa_keygen();
1269 }
1270
1271 static int cmd_help(int argc, char *argv[]) {
1272         usage(false);
1273         return 0;
1274 }
1275
1276 static int cmd_version(int argc, char *argv[]) {
1277         version();
1278         return 0;
1279 }
1280
1281 static const char *conffiles[] = {
1282         "tinc.conf",
1283         "tinc-up",
1284         "tinc-down",
1285         "subnet-up",
1286         "subnet-down",
1287         "host-up",
1288         "host-down",
1289         NULL,
1290 };
1291
1292 static int cmd_edit(int argc, char *argv[]) {
1293         if(argc != 2) {
1294                 fprintf(stderr, "Invalid number of arguments.\n");
1295                 return 1;
1296         }
1297
1298         char *filename = NULL;
1299
1300         if(strncmp(argv[1], "hosts/", 6)) {
1301                 for(int i = 0; conffiles[i]; i++) {
1302                         if(!strcmp(argv[1], conffiles[i])) {
1303                                 xasprintf(&filename, "%s/%s", confbase, argv[1]);
1304                                 break;
1305                         }
1306                 }
1307         } else {
1308                 argv[1] += 6;
1309         }
1310
1311         if(!filename) {
1312                 xasprintf(&filename, "%s/%s", hosts_dir, argv[1]);
1313                 char *dash = strchr(argv[1], '-');
1314                 if(dash) {
1315                         *dash++ = 0;
1316                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1317                                 fprintf(stderr, "Invalid configuration filename.\n");
1318                                 return 1;
1319                         }
1320                 }
1321         }
1322
1323 #ifndef HAVE_MINGW
1324         char *editor = getenv("VISUAL") ?: getenv("EDITOR") ?: "vi";
1325 #else
1326         char *editor = "edit"
1327 #endif
1328
1329         char *command;
1330         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1331         int result = system(command);
1332         if(result)
1333                 return result;
1334
1335         // Silently try notifying a running tincd of changes.
1336         fclose(stderr);
1337
1338         if(connect_tincd())
1339                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1340
1341         return 0;
1342 }
1343
1344 static const struct {
1345         const char *command;
1346         int (*function)(int argc, char *argv[]);
1347 } commands[] = {
1348         {"start", cmd_start},
1349         {"stop", cmd_stop},
1350         {"restart", cmd_restart},
1351         {"reload", cmd_reload},
1352         {"dump", cmd_dump},
1353         {"purge", cmd_purge},
1354         {"debug", cmd_debug},
1355         {"retry", cmd_retry},
1356         {"connect", cmd_connect},
1357         {"disconnect", cmd_disconnect},
1358         {"top", cmd_top},
1359         {"pcap", cmd_pcap},
1360         {"log", cmd_log},
1361         {"pid", cmd_pid},
1362         {"config", cmd_config},
1363         {"init", cmd_init},
1364         {"generate-keys", cmd_generate_keys},
1365         {"generate-rsa-keys", cmd_generate_rsa_keys},
1366         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1367         {"help", cmd_help},
1368         {"version", cmd_version},
1369         {"edit", cmd_edit},
1370         {NULL, NULL},
1371 };
1372
1373 int main(int argc, char *argv[]) {
1374         program_name = argv[0];
1375
1376         if(!parse_options(argc, argv))
1377                 return 1;
1378         
1379         make_names();
1380
1381         if(show_version) {
1382                 version();
1383                 return 0;
1384         }
1385
1386         if(show_help) {
1387                 usage(false);
1388                 return 0;
1389         }
1390
1391         if(optind >= argc) {
1392                 fprintf(stderr, "No command given.\n");
1393                 usage(true);
1394                 return 1;
1395         }
1396
1397         for(int i = 0; commands[i].command; i++) {
1398                 if(!strcasecmp(argv[optind], commands[i].command))
1399                         return commands[i].function(argc - optind, argv + optind);
1400         }
1401
1402         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
1403         usage(true);
1404         return 1;
1405 }