Allow dumping either directed or undirected graphs.
[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 #ifdef HAVE_READLINE
25 #include "readline/readline.h"
26 #include "readline/history.h"
27 #endif
28
29 #include "xalloc.h"
30 #include "protocol.h"
31 #include "control_common.h"
32 #include "ecdsagen.h"
33 #include "info.h"
34 #include "rsagen.h"
35 #include "utils.h"
36 #include "tincctl.h"
37 #include "top.h"
38
39 #ifdef HAVE_MINGW
40 #define mkdir(a, b) mkdir(a)
41 #endif
42
43
44 /* The name this program was run with. */
45 static char *program_name = NULL;
46
47 static char **orig_argv;
48 static int orig_argc;
49
50 /* If nonzero, display usage information and exit. */
51 static bool show_help = false;
52
53 /* If nonzero, print the version on standard output and exit.  */
54 static bool show_version = false;
55
56 static char *name = NULL;
57 static char *identname = NULL;                          /* program name for syslog */
58 static char *pidfilename = NULL;                        /* pid file location */
59 static char *confdir = NULL;
60 static char controlcookie[1024];
61 char *netname = NULL;
62 char *confbase = NULL;
63 static char *tinc_conf = NULL;
64 static char *hosts_dir = NULL;
65
66 // Horrible global variables...
67 static int pid = 0;
68 static int fd = -1;
69 static char line[4096];
70 static int code;
71 static int req;
72 static int result;
73 static bool force = false;
74 static bool tty = true;
75
76 #ifdef HAVE_MINGW
77 static struct WSAData wsa_state;
78 #endif
79
80 static struct option const long_options[] = {
81         {"config", required_argument, NULL, 'c'},
82         {"debug", optional_argument, NULL, 0},
83         {"no-detach", no_argument, NULL, 0},
84         {"mlock", no_argument, NULL, 0},
85         {"net", required_argument, NULL, 'n'},
86         {"help", no_argument, NULL, 1},
87         {"version", no_argument, NULL, 2},
88         {"pidfile", required_argument, NULL, 5},
89         {"logfile", required_argument, NULL, 0},
90         {"bypass-security", no_argument, NULL, 0},
91         {"chroot", no_argument, NULL, 0},
92         {"user", required_argument, NULL, 0},
93         {"option", required_argument, NULL, 0},
94         {"force", no_argument, NULL, 6},
95         {NULL, 0, NULL, 0}
96 };
97
98 static void version(void) {
99         printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
100                    VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
101         printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
102                         "See the AUTHORS file for a complete list.\n\n"
103                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
104                         "and you are welcome to redistribute it under certain conditions;\n"
105                         "see the file COPYING for details.\n");
106 }
107
108 static void usage(bool status) {
109         if(status)
110                 fprintf(stderr, "Try `%s --help\' for more information.\n",
111                                 program_name);
112         else {
113                 printf("Usage: %s [options] command\n\n", program_name);
114                 printf("Valid options are:\n"
115                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
116                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
117                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
118                                 "      --help              Display this help and exit.\n"
119                                 "      --version           Output version information and exit.\n"
120                                 "\n"
121                                 "Valid commands are:\n"
122                                 "  init [name]                Create initial configuration files.\n"
123                                 "  config                     Change configuration:\n"
124                                 "    [get] VARIABLE           - print current value of VARIABLE\n"
125                                 "    [set] VARIABLE VALUE     - set VARIABLE to VALUE\n"
126                                 "    add VARIABLE VALUE       - add VARIABLE with the given VALUE\n"
127                                 "    del VARIABLE [VALUE]     - remove VARIABLE [only ones with watching VALUE]\n"
128                                 "  start [tincd options]      Start tincd.\n"
129                                 "  stop                       Stop tincd.\n"
130                                 "  restart                    Restart tincd.\n"
131                                 "  reload                     Partially reload configuration of running tincd.\n"
132                                 "  pid                        Show PID of currently running tincd.\n"
133                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
134                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
135                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
136                                 "  dump                       Dump a list of one of the following things:\n"
137                                 "    nodes                    - all known nodes in the VPN\n"
138                                 "    edges                    - all known connections in the VPN\n"
139                                 "    subnets                  - all known subnets in the VPN\n"
140                                 "    connections              - all meta connections with ourself\n"
141                                 "    [di]graph                - graph of the VPN in dotty format\n"
142                                 "  info NODE|SUBNET|ADDRESS   Give information about a particular NODE, SUBNET or ADDRESS.\n"
143                                 "  purge                      Purge unreachable nodes\n"
144                                 "  debug N                    Set debug level\n"
145                                 "  retry                      Retry all outgoing connections\n"
146                                 "  disconnect NODE            Close meta connection with NODE\n"
147 #ifdef HAVE_CURSES
148                                 "  top                        Show real-time statistics\n"
149 #endif
150                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
151                                 "  log [level]                Dump log output [up to the specified level]\n"
152                                 "  export                     Export host configuration of local node to standard output\n"
153                                 "  export-all                 Export all host configuration files to standard output\n"
154                                 "  import [--force]           Import host configuration file(s) from standard input\n"
155                                 "\n");
156                 printf("Report bugs to tinc@tinc-vpn.org.\n");
157         }
158 }
159
160 static bool parse_options(int argc, char **argv) {
161         int r;
162         int option_index = 0;
163
164         while((r = getopt_long(argc, argv, "c:n:Dd::Lo:RU:", long_options, &option_index)) != EOF) {
165                 switch (r) {
166                         case 0:                         /* long option */
167                                 break;
168
169                         case 'c':                               /* config file */
170                                 confbase = xstrdup(optarg);
171                                 break;
172
173                         case 'n':                               /* net name given */
174                                 netname = xstrdup(optarg);
175                                 break;
176
177                         case 1:                                 /* show help */
178                                 show_help = true;
179                                 break;
180
181                         case 2:                                 /* show version */
182                                 show_version = true;
183                                 break;
184
185                         case 5:                                 /* open control socket here */
186                                 pidfilename = xstrdup(optarg);
187                                 break;
188
189                         case 6:
190                                 force = true;
191                                 break;
192
193                         case '?':
194                                 usage(true);
195                                 return false;
196
197                         default:
198                                 break;
199                 }
200         }
201
202         if(!netname && (netname = getenv("NETNAME")))
203                 netname = xstrdup(netname);
204
205         /* netname "." is special: a "top-level name" */
206
207         if(netname && (!*netname || !strcmp(netname, "."))) {
208                 free(netname);
209                 netname = NULL;
210         }
211
212         if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
213                 fprintf(stderr, "Invalid character in netname!\n");
214                 return false;
215         }
216
217         return true;
218 }
219
220 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
221         FILE *r;
222         char *directory;
223         char buf[PATH_MAX];
224         char buf2[PATH_MAX];
225
226         /* Check stdin and stdout */
227         if(ask && tty) {
228                 /* Ask for a file and/or directory name. */
229                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
230                                 what, filename);
231                 fflush(stdout);
232
233                 if(fgets(buf, sizeof buf, stdin) == NULL) {
234                         fprintf(stderr, "Error while reading stdin: %s\n",
235                                         strerror(errno));
236                         return NULL;
237                 }
238
239                 size_t len = strlen(buf);
240                 if(len)
241                         buf[--len] = 0;
242
243                 if(len)
244                         filename = buf;
245         }
246
247 #ifdef HAVE_MINGW
248         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
249 #else
250         if(filename[0] != '/') {
251 #endif
252                 /* The directory is a relative path or a filename. */
253                 directory = get_current_dir_name();
254                 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
255                 filename = buf2;
256         }
257
258         umask(0077);                            /* Disallow everything for group and other */
259
260         /* Open it first to keep the inode busy */
261
262         r = fopen(filename, mode);
263
264         if(!r) {
265                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
266                 return NULL;
267         }
268
269         return r;
270 }
271
272 /*
273   Generate a public/private ECDSA keypair, and ask for a file to store
274   them in.
275 */
276 static bool ecdsa_keygen(bool ask) {
277         ecdsa_t key;
278         FILE *f;
279         char *filename;
280
281         fprintf(stderr, "Generating ECDSA keypair:\n");
282
283         if(!ecdsa_generate(&key)) {
284                 fprintf(stderr, "Error during key generation!\n");
285                 return false;
286         } else
287                 fprintf(stderr, "Done.\n");
288
289         xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
290         f = ask_and_open(filename, "private ECDSA key", "a", ask);
291
292         if(!f)
293                 return false;
294   
295 #ifdef HAVE_FCHMOD
296         /* Make it unreadable for others. */
297         fchmod(fileno(f), 0600);
298 #endif
299                 
300         if(ftell(f))
301                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
302
303         ecdsa_write_pem_private_key(&key, f);
304
305         fclose(f);
306         free(filename);
307
308         if(name)
309                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
310         else
311                 xasprintf(&filename, "%s" SLASH "ecdsa_key.pub", confbase);
312
313         f = ask_and_open(filename, "public ECDSA key", "a", ask);
314
315         if(!f)
316                 return false;
317
318         if(ftell(f))
319                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
320
321         char *pubkey = ecdsa_get_base64_public_key(&key);
322         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
323         free(pubkey);
324
325         fclose(f);
326         free(filename);
327
328         return true;
329 }
330
331 /*
332   Generate a public/private RSA keypair, and ask for a file to store
333   them in.
334 */
335 static bool rsa_keygen(int bits, bool ask) {
336         rsa_t key;
337         FILE *f;
338         char *filename;
339
340         fprintf(stderr, "Generating %d bits keys:\n", bits);
341
342         if(!rsa_generate(&key, bits, 0x10001)) {
343                 fprintf(stderr, "Error during key generation!\n");
344                 return false;
345         } else
346                 fprintf(stderr, "Done.\n");
347
348         xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
349         f = ask_and_open(filename, "private RSA key", "a", ask);
350
351         if(!f)
352                 return false;
353   
354 #ifdef HAVE_FCHMOD
355         /* Make it unreadable for others. */
356         fchmod(fileno(f), 0600);
357 #endif
358                 
359         if(ftell(f))
360                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
361
362         rsa_write_pem_private_key(&key, f);
363
364         fclose(f);
365         free(filename);
366
367         if(name)
368                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
369         else
370                 xasprintf(&filename, "%s" SLASH "rsa_key.pub", confbase);
371
372         f = ask_and_open(filename, "public RSA key", "a", ask);
373
374         if(!f)
375                 return false;
376
377         if(ftell(f))
378                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
379
380         rsa_write_pem_public_key(&key, f);
381
382         fclose(f);
383         free(filename);
384
385         return true;
386 }
387
388 /*
389   Set all files and paths according to netname
390 */
391 static void make_names(void) {
392 #ifdef HAVE_MINGW
393         HKEY key;
394         char installdir[1024] = "";
395         long len = sizeof installdir;
396 #endif
397
398         if(netname)
399                 xasprintf(&identname, "tinc.%s", netname);
400         else
401                 identname = xstrdup("tinc");
402
403 #ifdef HAVE_MINGW
404         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
405                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
406                         if(!confbase) {
407                                 if(netname)
408                                         xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
409                                 else
410                                         xasprintf(&confbase, "%s", installdir);
411                         }
412                 }
413                 if(!pidfilename)
414                         xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
415                 RegCloseKey(key);
416         }
417
418         if(!*installdir) {
419 #endif
420         confdir = xstrdup(CONFDIR);
421
422         if(!pidfilename)
423                 xasprintf(&pidfilename, "%s" SLASH "run" SLASH "%s.pid", LOCALSTATEDIR, identname);
424
425         if(netname) {
426                 if(!confbase)
427                         xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
428                 else
429                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
430         } else {
431                 if(!confbase)
432                         xasprintf(&confbase, CONFDIR SLASH "tinc");
433         }
434
435 #ifdef HAVE_MINGW
436         } else
437                 confdir = xstrdup(installdir);
438 #endif
439
440         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
441         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
442 }
443
444 static char buffer[4096];
445 static size_t blen = 0;
446
447 bool recvline(int fd, char *line, size_t len) {
448         char *newline = NULL;
449
450         while(!(newline = memchr(buffer, '\n', blen))) {
451                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
452                 if(result == -1 && errno == EINTR)
453                         continue;
454                 else if(result <= 0)
455                         return false;
456                 blen += result;
457         }
458
459         if(newline - buffer >= len)
460                 return false;
461
462         len = newline - buffer;
463
464         memcpy(line, buffer, len);
465         line[len] = 0;
466         memmove(buffer, newline + 1, blen - len - 1);
467         blen -= len + 1;
468
469         return true;
470 }
471
472 static bool recvdata(int fd, char *data, size_t len) {
473         while(blen < len) {
474                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
475                 if(result == -1 && errno == EINTR)
476                         continue;
477                 else if(result <= 0)
478                         return false;
479                 blen += result;
480         }
481
482         memcpy(data, buffer, len);
483         memmove(buffer, buffer + len, blen - len);
484         blen -= len;
485
486         return true;
487 }
488
489 bool sendline(int fd, char *format, ...) {
490         static char buffer[4096];
491         char *p = buffer;
492         int blen = 0;
493         va_list ap;
494
495         va_start(ap, format);
496         blen = vsnprintf(buffer, sizeof buffer, format, ap);
497         va_end(ap);
498
499         if(blen < 1 || blen >= sizeof buffer)
500                 return false;
501
502         buffer[blen] = '\n';
503         blen++;
504
505         while(blen) {
506                 int result = send(fd, p, blen, 0);
507                 if(result == -1 && errno == EINTR)
508                         continue;
509                 else if(result <= 0)
510                         return false;
511                 p += result;
512                 blen -= result;
513         }
514
515         return true;    
516 }
517
518 static void pcap(int fd, FILE *out, int snaplen) {
519         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
520         char data[9018];
521
522         struct {
523                 uint32_t magic;
524                 uint16_t major;
525                 uint16_t minor;
526                 uint32_t tz_offset;
527                 uint32_t tz_accuracy;
528                 uint32_t snaplen;
529                 uint32_t ll_type;
530         } header = {
531                 0xa1b2c3d4,
532                 2, 4,
533                 0, 0,
534                 snaplen ?: sizeof data,
535                 1,
536         };
537
538         struct {
539                 uint32_t tv_sec;
540                 uint32_t tv_usec;
541                 uint32_t len;
542                 uint32_t origlen;
543         } packet;
544
545         struct timeval tv;
546
547         fwrite(&header, sizeof header, 1, out);
548         fflush(out);
549
550         char line[32];
551         while(recvline(fd, line, sizeof line)) {
552                 int code, req, len;
553                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
554                 gettimeofday(&tv, NULL);
555                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
556                         break;
557                 if(!recvdata(fd, data, len))
558                         break;
559                 packet.tv_sec = tv.tv_sec;
560                 packet.tv_usec = tv.tv_usec;
561                 packet.len = len;
562                 packet.origlen = len;
563                 fwrite(&packet, sizeof packet, 1, out);
564                 fwrite(data, len, 1, out);
565                 fflush(out);
566         }
567 }
568
569 static void logcontrol(int fd, FILE *out, int level) {
570         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
571         char data[1024];
572         char line[32];
573
574         while(recvline(fd, line, sizeof line)) {
575                 int code, req, len;
576                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
577                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
578                         break;
579                 if(!recvdata(fd, data, len))
580                         break;
581                 fwrite(data, len, 1, out);
582                 fputc('\n', out);
583                 fflush(out);
584         }
585 }
586
587 #ifdef HAVE_MINGW
588 static bool remove_service(void) {
589         SC_HANDLE manager = NULL;
590         SC_HANDLE service = NULL;
591         SERVICE_STATUS status = {0};
592
593         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
594         if(!manager) {
595                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
596                 return false;
597         }
598
599         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
600
601         if(!service) {
602                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
603                 return false;
604         }
605
606         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
607                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
608         else
609                 fprintf(stderr, "%s service stopped\n", identname);
610
611         if(!DeleteService(service)) {
612                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
613                 return false;
614         }
615
616         fprintf(stderr, "%s service removed\n", identname);
617
618         return true;
619 }
620 #endif
621
622 static bool connect_tincd(bool verbose) {
623         if(fd >= 0)
624                 return true;
625
626         FILE *f = fopen(pidfilename, "r");
627         if(!f) {
628                 if(verbose)
629                         fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
630                 return false;
631         }
632
633         char host[128];
634         char port[128];
635
636         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
637                 if(verbose)
638                         fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
639                 fclose(f);
640                 return false;
641         }
642
643         fclose(f);
644
645 #ifdef HAVE_MINGW
646         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
647                 if(verbose)
648                         fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
649                 return false;
650         }
651 #endif
652
653         struct addrinfo hints = {
654                 .ai_family = AF_UNSPEC,
655                 .ai_socktype = SOCK_STREAM,
656                 .ai_protocol = IPPROTO_TCP,
657                 .ai_flags = 0,
658         };
659
660         struct addrinfo *res = NULL;
661
662         if(getaddrinfo(host, port, &hints, &res) || !res) {
663                 if(verbose)
664                         fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
665                 return false;
666         }
667
668         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
669         if(fd < 0) {
670                 if(verbose)
671                         fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
672                 return false;
673         }
674
675 #ifdef HAVE_MINGW
676         unsigned long arg = 0;
677
678         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
679                 if(verbose)
680                         fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
681         }
682 #endif
683
684         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
685                 if(verbose)
686                         fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
687                 return false;
688         }
689
690         freeaddrinfo(res);
691
692         char data[4096];
693         int version;
694
695         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
696                 if(verbose)
697                         fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
698                 return false;
699         }
700
701         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
702         
703         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
704                 if(verbose)
705                         fprintf(stderr, "Could not fully establish control socket connection\n");
706                 return false;
707         }
708
709         return true;
710 }
711
712
713 static int cmd_start(int argc, char *argv[]) {
714         if(connect_tincd(false)) {
715                 if(netname)
716                         fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
717                 else
718                         fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
719                 return 0;
720         }
721
722         char *c;
723         char *slash = strrchr(program_name, '/');
724
725 #ifdef HAVE_MINGW
726         if ((c = strrchr(program_name, '\\')) > slash)
727                 slash = c;
728 #endif
729
730         if (slash++)
731                 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
732         else
733                 c = "tincd";
734
735         int nargc = 0;
736         char **nargv = xmalloc_and_zero((orig_argc + argc) * sizeof *nargv);
737
738         for(int i = 0; i < orig_argc; i++)
739                 nargv[nargc++] = orig_argv[i];
740         for(int i = 1; i < argc; i++)
741                 nargv[nargc++] = argv[i];
742
743 #ifdef HAVE_MINGW
744         execvp(c, nargv);
745         fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
746         return 1;
747 #else
748         pid_t pid = fork();
749         if(pid == -1) {
750                 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
751                 return 1;
752         }
753
754         if(!pid)
755                 exit(execvp(c, nargv));
756         
757         int status = -1;
758         if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
759                 fprintf(stderr, "Error starting %s\n", c);
760                 return 1;
761         }
762
763         return 0;
764 #endif
765 }
766
767 static int cmd_stop(int argc, char *argv[]) {
768 #ifndef HAVE_MINGW
769         if(!connect_tincd(true)) {
770                 if(pid) {
771                         if(kill(pid, SIGTERM)) 
772                                 return 1;
773                         fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
774                         return 0;
775                 }
776
777                 return 1;
778         }
779
780         sendline(fd, "%d %d", CONTROL, REQ_STOP);
781         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
782                 fprintf(stderr, "Could not stop tinc daemon.\n");
783                 return 1;
784         }
785 #else
786         if(!remove_service())
787                 return 1;
788 #endif
789         close(fd);
790         pid = 0;
791         fd = -1;
792
793         return 0;
794 }
795
796 static int cmd_restart(int argc, char *argv[]) {
797         cmd_stop(argc, argv);
798         return cmd_start(argc, argv);
799 }
800
801 static int cmd_reload(int argc, char *argv[]) {
802         if(!connect_tincd(true))
803                 return 1;
804
805         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
806         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
807                 fprintf(stderr, "Could not reload configuration.\n");
808                 return 1;
809         }
810
811         return 0;
812
813 }
814
815 static int cmd_dump(int argc, char *argv[]) {
816         if(argc != 2) {
817                 fprintf(stderr, "Invalid number of arguments.\n");
818                 usage(true);
819                 return 1;
820         }
821
822         if(!connect_tincd(true))
823                 return 1;
824
825         int do_graph = 0;
826
827         if(!strcasecmp(argv[1], "nodes"))
828                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
829         else if(!strcasecmp(argv[1], "edges"))
830                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
831         else if(!strcasecmp(argv[1], "subnets"))
832                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
833         else if(!strcasecmp(argv[1], "connections"))
834                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
835         else if(!strcasecmp(argv[1], "graph")) {
836                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
837                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
838                 do_graph = 1;
839         } else if(!strcasecmp(argv[1], "digraph")) {
840                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
841                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
842                 do_graph = 2;
843         } else {
844                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
845                 usage(true);
846                 return 1;
847         }
848
849         if(do_graph == 1)
850                 printf("graph {\n");
851         else if(do_graph == 2)
852                 printf("digraph {\n");
853
854         while(recvline(fd, line, sizeof line)) {
855                 char node1[4096], node2[4096];
856                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
857                 if(n == 2) {
858                         if(do_graph && req == REQ_DUMP_NODES)
859                                 continue;
860                         else {
861                                 if(do_graph)
862                                         printf("}\n");
863                                 return 0;
864                         }
865                 }
866                 if(n < 2)
867                         break;
868
869                 if(!do_graph) {
870                         char node[4096];
871                         char from[4096];
872                         char to[4096];
873                         char subnet[4096];
874                         char host[4096];
875                         char port[4096];
876                         char via[4096];
877                         char nexthop[4096];
878                         int cipher, digest, maclength, compression, distance, socket, weight;
879                         short int pmtu, minmtu, maxmtu;
880                         unsigned int options, status;
881                         long int last_state_change;
882
883                         switch(req) {
884                                 case REQ_DUMP_NODES: {
885                                         int n = sscanf(line, "%*d %*d %s %s port %s %d %d %d %d %x %x %s %s %d %hd %hd %hd %ld", node, host, port, &cipher, &digest, &maclength, &compression, &options, &status, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change);
886                                         if(n != 16) {
887                                                 fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
888                                                 return 1;
889                                         }
890                                         printf("%s at %s port %s cipher %d digest %d maclength %d compression %d options %x status %04x nexthop %s via %s distance %d pmtu %hd (min %hd max %hd)\n",
891                                                         node, host, port, cipher, digest, maclength, compression, options, status, nexthop, via, distance, pmtu, minmtu, maxmtu);
892                                 } break;
893
894                                 case REQ_DUMP_EDGES: {
895                                         int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
896                                         if(n != 6) {
897                                                 fprintf(stderr, "Unable to parse edge dump from tincd.\n");
898                                                 return 1;
899                                         }
900                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
901                                 } break;
902
903                                 case REQ_DUMP_SUBNETS: {
904                                         int n = sscanf(line, "%*d %*d %s %s", subnet, node);
905                                         if(n != 2) {
906                                                 fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
907                                                 return 1;
908                                         }
909                                         printf("%s owner %s\n", strip_weight(subnet), node);
910                                 } break;
911
912                                 case REQ_DUMP_CONNECTIONS: {
913                                         int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status);
914                                         if(n != 6) {
915                                                 fprintf(stderr, "Unable to parse connection dump from tincd.\n");
916                                                 return 1;
917                                         }
918                                         printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status);
919                                 } break;
920
921                                 default:
922                                         fprintf(stderr, "Unable to parse dump from tincd.\n");
923                                         return 1;
924                         }
925                 } else {
926                         if(req == REQ_DUMP_NODES)
927                                 printf(" %s [label = \"%s\"];\n", node1, node1);
928                         else {
929                                 if(do_graph == 1 && strcmp(node1, node2) > 0)
930                                         printf(" %s -- %s;\n", node1, node2);
931                                 else if(do_graph == 2)
932                                         printf(" %s -> %s;\n", node1, node2);
933                         }
934                 }
935         }
936
937         fprintf(stderr, "Error receiving dump.\n");
938         return 1;
939 }
940
941 static int cmd_purge(int argc, char *argv[]) {
942         if(!connect_tincd(true))
943                 return 1;
944
945         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
946         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
947                 fprintf(stderr, "Could not purge old information.\n");
948                 return 1;
949         }
950
951         return 0;
952 }
953
954 static int cmd_debug(int argc, char *argv[]) {
955         if(argc != 2) {
956                 fprintf(stderr, "Invalid number of arguments.\n");
957                 return 1;
958         }
959
960         if(!connect_tincd(true))
961                 return 1;
962
963         int debuglevel = atoi(argv[1]);
964         int origlevel;
965
966         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
967         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
968                 fprintf(stderr, "Could not set debug level.\n");
969                 return 1;
970         }
971
972         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
973         return 0;
974 }
975
976 static int cmd_retry(int argc, char *argv[]) {
977         if(!connect_tincd(true))
978                 return 1;
979
980         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
981         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
982                 fprintf(stderr, "Could not retry outgoing connections.\n");
983                 return 1;
984         }
985
986         return 0;
987 }
988
989 static int cmd_connect(int argc, char *argv[]) {
990         if(argc != 2) {
991                 fprintf(stderr, "Invalid number of arguments.\n");
992                 return 1;
993         }
994
995         if(!check_id(argv[1])) {
996                 fprintf(stderr, "Invalid name for node.\n");
997                 return 1;
998         }
999
1000         if(!connect_tincd(true))
1001                 return 1;
1002
1003         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1004         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1005                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1006                 return 1;
1007         }
1008
1009         return 0;
1010 }
1011
1012 static int cmd_disconnect(int argc, char *argv[]) {
1013         if(argc != 2) {
1014                 fprintf(stderr, "Invalid number of arguments.\n");
1015                 return 1;
1016         }
1017
1018         if(!check_id(argv[1])) {
1019                 fprintf(stderr, "Invalid name for node.\n");
1020                 return 1;
1021         }
1022
1023         if(!connect_tincd(true))
1024                 return 1;
1025
1026         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1027         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1028                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1029                 return 1;
1030         }
1031
1032         return 0;
1033 }
1034
1035 static int cmd_top(int argc, char *argv[]) {
1036 #ifdef HAVE_CURSES
1037         if(!connect_tincd(true))
1038                 return 1;
1039
1040         top(fd);
1041         return 0;
1042 #else
1043         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1044         return 1;
1045 #endif
1046 }
1047
1048 static int cmd_pcap(int argc, char *argv[]) {
1049         if(!connect_tincd(true))
1050                 return 1;
1051
1052         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1053         return 0;
1054 }
1055
1056 static int cmd_log(int argc, char *argv[]) {
1057         if(!connect_tincd(true))
1058                 return 1;
1059
1060         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1061         return 0;
1062 }
1063
1064 static int cmd_pid(int argc, char *argv[]) {
1065         if(!connect_tincd(true) && !pid)
1066                 return 1;
1067
1068         printf("%d\n", pid);
1069         return 0;
1070 }
1071
1072 static int rstrip(char *value) {
1073         int len = strlen(value);
1074         while(len && strchr("\t\r\n ", value[len - 1]))
1075                 value[--len] = 0;
1076         return len;
1077 }
1078
1079 static char *get_my_name() {
1080         FILE *f = fopen(tinc_conf, "r");
1081         if(!f) {
1082                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1083                 return NULL;
1084         }
1085
1086         char buf[4096];
1087         char *value;
1088         while(fgets(buf, sizeof buf, f)) {
1089                 int len = strcspn(buf, "\t =");
1090                 value = buf + len;
1091                 value += strspn(value, "\t ");
1092                 if(*value == '=') {
1093                         value++;
1094                         value += strspn(value, "\t ");
1095                 }
1096                 if(!rstrip(value))
1097                         continue;
1098                 buf[len] = 0;
1099                 if(strcasecmp(buf, "Name"))
1100                         continue;
1101                 if(*value) {
1102                         fclose(f);
1103                         return strdup(value);
1104                 }
1105         }
1106
1107         fclose(f);
1108         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1109         return NULL;
1110 }
1111
1112 #define VAR_SERVER 1    /* Should be in tinc.conf */
1113 #define VAR_HOST 2      /* Can be in host config file */
1114 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
1115 #define VAR_OBSOLETE 8  /* Should not be used anymore */
1116
1117 static struct {
1118         const char *name;
1119         int type;
1120 } const variables[] = {
1121         /* Server configuration */
1122         {"AddressFamily", VAR_SERVER},
1123         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1124         {"BindToInterface", VAR_SERVER},
1125         {"Broadcast", VAR_SERVER},
1126         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1127         {"DecrementTTL", VAR_SERVER},
1128         {"Device", VAR_SERVER},
1129         {"DeviceType", VAR_SERVER},
1130         {"DirectOnly", VAR_SERVER},
1131         {"ECDSAPrivateKeyFile", VAR_SERVER},
1132         {"ExperimentalProtocol", VAR_SERVER},
1133         {"Forwarding", VAR_SERVER},
1134         {"GraphDumpFile", VAR_SERVER},
1135         {"Hostnames", VAR_SERVER},
1136         {"IffOneQueue", VAR_SERVER},
1137         {"Interface", VAR_SERVER},
1138         {"KeyExpire", VAR_SERVER},
1139         {"LocalDiscovery", VAR_SERVER},
1140         {"MACExpire", VAR_SERVER},
1141         {"MaxOutputBufferSize", VAR_SERVER},
1142         {"MaxTimeout", VAR_SERVER},
1143         {"Mode", VAR_SERVER},
1144         {"Name", VAR_SERVER},
1145         {"PingInterval", VAR_SERVER},
1146         {"PingTimeout", VAR_SERVER},
1147         {"PriorityInheritance", VAR_SERVER},
1148         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1149         {"PrivateKeyFile", VAR_SERVER},
1150         {"ProcessPriority", VAR_SERVER},
1151         {"Proxy", VAR_SERVER},
1152         {"ReplayWindow", VAR_SERVER},
1153         {"StrictSubnets", VAR_SERVER},
1154         {"TunnelServer", VAR_SERVER},
1155         {"UDPRcvBuf", VAR_SERVER},
1156         {"UDPSndBuf", VAR_SERVER},
1157         {"VDEGroup", VAR_SERVER},
1158         {"VDEPort", VAR_SERVER},
1159         /* Host configuration */
1160         {"Address", VAR_HOST | VAR_MULTIPLE},
1161         {"Cipher", VAR_SERVER | VAR_HOST},
1162         {"ClampMSS", VAR_SERVER | VAR_HOST},
1163         {"Compression", VAR_SERVER | VAR_HOST},
1164         {"Digest", VAR_SERVER | VAR_HOST},
1165         {"ECDSAPublicKey", VAR_HOST},
1166         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1167         {"IndirectData", VAR_SERVER | VAR_HOST},
1168         {"MACLength", VAR_SERVER | VAR_HOST},
1169         {"PMTU", VAR_SERVER | VAR_HOST},
1170         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1171         {"Port", VAR_HOST},
1172         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1173         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1174         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1175         {"TCPOnly", VAR_SERVER | VAR_HOST},
1176         {"Weight", VAR_HOST},
1177         {NULL, 0}
1178 };
1179
1180 static int cmd_config(int argc, char *argv[]) {
1181         if(argc < 2) {
1182                 fprintf(stderr, "Invalid number of arguments.\n");
1183                 return 1;
1184         }
1185
1186         int action = -2;
1187         if(!strcasecmp(argv[1], "get")) {
1188                 argv++, argc--;
1189         } else if(!strcasecmp(argv[1], "add")) {
1190                 argv++, argc--, action = 1;
1191         } else if(!strcasecmp(argv[1], "del")) {
1192                 argv++, argc--, action = -1;
1193         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1194                 argv++, argc--, action = 0;
1195         }
1196
1197         if(argc < 2) {
1198                 fprintf(stderr, "Invalid number of arguments.\n");
1199                 return 1;
1200         }
1201
1202         // Concatenate the rest of the command line
1203         strncpy(line, argv[1], sizeof line - 1);
1204         for(int i = 2; i < argc; i++) {
1205                 strncat(line, " ", sizeof line - 1 - strlen(line));
1206                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1207         }
1208
1209         // Liberal parsing into node name, variable name and value.
1210         char *node = NULL;
1211         char *variable;
1212         char *value;
1213         int len;
1214
1215         len = strcspn(line, "\t =");
1216         value = line + len;
1217         value += strspn(value, "\t ");
1218         if(*value == '=') {
1219                 value++;
1220                 value += strspn(value, "\t ");
1221         }
1222         line[len] = '\0';
1223         variable = strchr(line, '.');
1224         if(variable) {
1225                 node = line;
1226                 *variable++ = 0;
1227         } else {
1228                 variable = line;
1229         }
1230
1231         if(!*variable) {
1232                 fprintf(stderr, "No variable given.\n");
1233                 return 1;
1234         }
1235
1236         if(action >= 0 && !*value) {
1237                 fprintf(stderr, "No value for variable given.\n");
1238                 return 1;
1239         }
1240
1241         if(action < -1 && *value)
1242                 action = 0;
1243
1244         /* Some simple checks. */
1245         bool found = false;
1246
1247         for(int i = 0; variables[i].name; i++) {
1248                 if(strcasecmp(variables[i].name, variable))
1249                         continue;
1250
1251                 found = true;
1252                 variable = (char *)variables[i].name;
1253
1254                 /* Discourage use of obsolete variables. */
1255
1256                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1257                         if(force) {
1258                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1259                         } else {
1260                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1261                                 return 1;
1262                         }
1263                 }
1264
1265                 /* Don't put server variables in host config files */
1266
1267                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1268                         if(force) {
1269                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1270                         } else {
1271                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1272                                 return 1;
1273                         }
1274                 }
1275
1276                 /* Should this go into our own host config file? */
1277
1278                 if(!node && !(variables[i].type & VAR_SERVER)) {
1279                         node = get_my_name();
1280                         if(!node)
1281                                 return 1;
1282                 }
1283
1284                 break;
1285         }
1286
1287         if(node && !check_id(node)) {
1288                 fprintf(stderr, "Invalid name for node.\n");
1289                 return 1;
1290         }
1291
1292         if(!found) {
1293                 if(force || action < 0) {
1294                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1295                 } else {
1296                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1297                         return 1;
1298                 }
1299         }
1300
1301         // Open the right configuration file.
1302         char *filename;
1303         if(node)
1304                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1305         else
1306                 filename = tinc_conf;
1307
1308         FILE *f = fopen(filename, "r");
1309         if(!f) {
1310                 if(action < 0 || errno != ENOENT) {
1311                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1312                         return 1;
1313                 }
1314
1315                 // If it doesn't exist, create it.
1316                 f = fopen(filename, "a+");
1317                 if(!f) {
1318                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1319                         return 1;
1320                 } else {
1321                         fprintf(stderr, "Created configuration file %s.\n", filename);
1322                 }
1323         }
1324
1325         char *tmpfile = NULL;
1326         FILE *tf = NULL;
1327
1328         if(action >= -1) {
1329                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1330                 tf = fopen(tmpfile, "w");
1331                 if(!tf) {
1332                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1333                         fclose(f);
1334                         return 1;
1335                 }
1336         }
1337
1338         // Copy the file, making modifications on the fly, unless we are just getting a value.
1339         char buf1[4096];
1340         char buf2[4096];
1341         bool set = false;
1342         bool removed = false;
1343         found = false;
1344
1345         while(fgets(buf1, sizeof buf1, f)) {
1346                 buf1[sizeof buf1 - 1] = 0;
1347                 strncpy(buf2, buf1, sizeof buf2);
1348
1349                 // Parse line in a simple way
1350                 char *bvalue;
1351                 int len;
1352
1353                 len = strcspn(buf2, "\t =");
1354                 bvalue = buf2 + len;
1355                 bvalue += strspn(bvalue, "\t ");
1356                 if(*bvalue == '=') {
1357                         bvalue++;
1358                         bvalue += strspn(bvalue, "\t ");
1359                 }
1360                 rstrip(bvalue);
1361                 buf2[len] = '\0';
1362
1363                 // Did it match?
1364                 if(!strcasecmp(buf2, variable)) {
1365                         // Get
1366                         if(action < -1) {
1367                                 found = true;
1368                                 printf("%s\n", bvalue);
1369                         // Del
1370                         } else if(action == -1) {
1371                                 if(!*value || !strcasecmp(bvalue, value)) {
1372                                         removed = true;
1373                                         continue;
1374                                 }
1375                         // Set
1376                         } else if(action == 0) {
1377                                 // Already set? Delete the rest...
1378                                 if(set)
1379                                         continue;
1380                                 // Otherwise, replace.
1381                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1382                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1383                                         return 1;
1384                                 }
1385                                 set = true;
1386                                 continue;
1387                         }
1388                 }
1389
1390                 if(action >= -1) {
1391                         // Copy original line...
1392                         if(fputs(buf1, tf) < 0) {
1393                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1394                                 return 1;
1395                         }
1396
1397                         // Add newline if it is missing...
1398                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1399                                 if(fputc('\n', tf) < 0) {
1400                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1401                                         return 1;
1402                                 }
1403                         }
1404                 }
1405         }
1406
1407         // Make sure we read everything...
1408         if(ferror(f) || !feof(f)) {
1409                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1410                 return 1;
1411         }
1412
1413         if(fclose(f)) {
1414                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1415                 return 1;
1416         }
1417
1418         // Add new variable if necessary.
1419         if(action > 0 || (action == 0 && !set)) {
1420                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1421                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1422                         return 1;
1423                 }
1424         }
1425
1426         if(action < -1) {
1427                 if(!found)
1428                         fprintf(stderr, "No matching configuration variables found.\n");
1429                 return 0;
1430         }
1431
1432         // Make sure we wrote everything...
1433         if(fclose(tf)) {
1434                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1435                 return 1;
1436         }
1437
1438         // Could we find what we had to remove?
1439         if(action < 0 && !removed) {
1440                 remove(tmpfile);
1441                 fprintf(stderr, "No configuration variables deleted.\n");
1442                 return *value;
1443         }
1444
1445         // Replace the configuration file with the new one
1446 #ifdef HAVE_MINGW
1447         if(remove(filename)) {
1448                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1449                 return 1;
1450         }
1451 #endif
1452         if(rename(tmpfile, filename)) {
1453                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1454                 return 1;
1455         }
1456
1457         // Silently try notifying a running tincd of changes.
1458         if(connect_tincd(false))
1459                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1460
1461         return 0;
1462 }
1463
1464 bool check_id(const char *name) {
1465         if(!name || !*name)
1466                 return false;
1467
1468         for(int i = 0; i < strlen(name); i++) {
1469                 if(!isalnum(name[i]) && name[i] != '_')
1470                         return false;
1471         }
1472
1473         return true;
1474 }
1475
1476 static int cmd_init(int argc, char *argv[]) {
1477         if(!access(tinc_conf, F_OK)) {
1478                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1479                 return 1;
1480         }
1481
1482         if(argc < 2) {
1483                 if(tty) {
1484                         char buf[1024];
1485                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1486                         fflush(stdout);
1487                         if(!fgets(buf, sizeof buf, stdin)) {
1488                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1489                                 return 1;
1490                         }
1491                         int len = rstrip(buf);
1492                         if(!len) {
1493                                 fprintf(stderr, "No name given!\n");
1494                                 return 1;
1495                         }
1496                         name = strdup(buf);
1497                 } else {
1498                         fprintf(stderr, "No Name given!\n");
1499                         return 1;
1500                 }
1501         } else {
1502                 name = strdup(argv[1]);
1503                 if(!*name) {
1504                         fprintf(stderr, "No Name given!\n");
1505                         return 1;
1506                 }
1507         }
1508
1509         if(!check_id(name)) {
1510                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1511                 return 1;
1512         }
1513
1514         if(mkdir(confdir, 0755) && errno != EEXIST) {
1515                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1516                 return 1;
1517         }
1518
1519         if(mkdir(confbase, 0755) && errno != EEXIST) {
1520                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1521                 return 1;
1522         }
1523
1524         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1525                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1526                 return 1;
1527         }
1528
1529         FILE *f = fopen(tinc_conf, "w");
1530         if(!f) {
1531                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1532                 return 1;
1533         }
1534
1535         fprintf(f, "Name = %s\n", name);
1536         fclose(f);
1537
1538         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1539                 return 1;
1540
1541 #ifndef HAVE_MINGW
1542         char *filename;
1543         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1544         if(access(filename, F_OK)) {
1545                 FILE *f = fopen(filename, "w");
1546                 if(!f) {
1547                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1548                         return 1;
1549                 }
1550                 fchmod(fileno(f), 0755);
1551                 fprintf(f, "#!/bin/sh\n\necho 'Unconfigured tinc-up script, please edit!'\n\n#ifconfig $INTERFACE <your vpn IP address> netmask <netmask of whole VPN>\n");
1552                 fclose(f);
1553         }
1554 #endif
1555
1556         return 0;
1557
1558 }
1559
1560 static int cmd_generate_keys(int argc, char *argv[]) {
1561         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1562 }
1563
1564 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1565         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1566 }
1567
1568 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1569         return !ecdsa_keygen(true);
1570 }
1571
1572 static int cmd_help(int argc, char *argv[]) {
1573         usage(false);
1574         return 0;
1575 }
1576
1577 static int cmd_version(int argc, char *argv[]) {
1578         version();
1579         return 0;
1580 }
1581
1582 static int cmd_info(int argc, char *argv[]) {
1583         if(argc != 2) {
1584                 fprintf(stderr, "Invalid number of arguments.\n");
1585                 return 1;
1586         }
1587
1588         if(!connect_tincd(true))
1589                 return 1;
1590
1591         return info(fd, argv[1]);
1592 }
1593
1594 static const char *conffiles[] = {
1595         "tinc.conf",
1596         "tinc-up",
1597         "tinc-down",
1598         "subnet-up",
1599         "subnet-down",
1600         "host-up",
1601         "host-down",
1602         NULL,
1603 };
1604
1605 static int cmd_edit(int argc, char *argv[]) {
1606         if(argc != 2) {
1607                 fprintf(stderr, "Invalid number of arguments.\n");
1608                 return 1;
1609         }
1610
1611         char *filename = NULL;
1612
1613         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1614                 for(int i = 0; conffiles[i]; i++) {
1615                         if(!strcmp(argv[1], conffiles[i])) {
1616                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1617                                 break;
1618                         }
1619                 }
1620         } else {
1621                 argv[1] += 6;
1622         }
1623
1624         if(!filename) {
1625                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1626                 char *dash = strchr(argv[1], '-');
1627                 if(dash) {
1628                         *dash++ = 0;
1629                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1630                                 fprintf(stderr, "Invalid configuration filename.\n");
1631                                 return 1;
1632                         }
1633                 }
1634         }
1635
1636         char *command;
1637 #ifndef HAVE_MINGW
1638         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1639 #else
1640         xasprintf(&command, "edit \"%s\"", filename);
1641 #endif
1642         int result = system(command);
1643         if(result)
1644                 return result;
1645
1646         // Silently try notifying a running tincd of changes.
1647         if(connect_tincd(false))
1648                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1649
1650         return 0;
1651 }
1652
1653 static int export(const char *name, FILE *out) {
1654         char *filename;
1655         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1656         FILE *in = fopen(filename, "r");
1657         if(!in) {
1658                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1659                 return 1;
1660         }
1661
1662         fprintf(out, "Name = %s\n", name);
1663         char buf[4096];
1664         while(fgets(buf, sizeof buf, in)) {
1665                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1666                         fputs(buf, out);
1667         }
1668
1669         if(ferror(in)) {
1670                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1671                 fclose(in);
1672                 return 1;
1673         }
1674
1675         fclose(in);
1676         return 0;
1677 }
1678
1679 static int cmd_export(int argc, char *argv[]) {
1680         char *name = get_my_name();
1681         if(!name)
1682                 return 1;
1683
1684         return export(name, stdout);
1685 }
1686
1687 static int cmd_export_all(int argc, char *argv[]) {
1688         DIR *dir = opendir(hosts_dir);
1689         if(!dir) {
1690                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1691                 return 1;
1692         }
1693
1694         bool first = true;
1695         int result = 0;
1696         struct dirent *ent;
1697
1698         while((ent = readdir(dir))) {
1699                 if(!check_id(ent->d_name))
1700                         continue;
1701
1702                 if(first)
1703                         first = false;
1704                 else
1705                         printf("#---------------------------------------------------------------#\n");
1706
1707                 result |= export(ent->d_name, stdout);
1708         }
1709
1710         closedir(dir);
1711         return result;
1712 }
1713
1714 static int cmd_import(int argc, char *argv[]) {
1715         FILE *in = stdin;
1716         FILE *out = NULL;
1717
1718         char buf[4096];
1719         char name[4096];
1720         char *filename;
1721         int count = 0;
1722         bool firstline = true;
1723
1724         while(fgets(buf, sizeof buf, in)) {
1725                 if(sscanf(buf, "Name = %s", name) == 1) {
1726                         if(!check_id(name)) {
1727                                 fprintf(stderr, "Invalid Name in input!\n");
1728                                 return 1;
1729                         }
1730
1731                         if(out)
1732                                 fclose(out);
1733
1734                         free(filename);
1735                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1736
1737                         if(!force && !access(filename, F_OK)) {
1738                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1739                                 out = NULL;
1740                                 continue;
1741                         }
1742
1743                         out = fopen(filename, "w");
1744                         if(!out) {
1745                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1746                                 return 1;
1747                         }
1748
1749                         count++;
1750                         firstline = false;
1751                         continue;
1752                 } else if(firstline) {
1753                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1754                         firstline = false;
1755                 }
1756
1757
1758                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1759                         continue;
1760
1761                 if(out) {
1762                         if(fputs(buf, out) < 0) {
1763                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1764                                 return 1;
1765                         }
1766                 }
1767         }
1768
1769         if(out)
1770                 fclose(out);
1771
1772         if(count) {
1773                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1774                 return 0;
1775         } else {
1776                 fprintf(stderr, "No host configuration files imported.\n");
1777                 return 1;
1778         }
1779 }
1780
1781 static const struct {
1782         const char *command;
1783         int (*function)(int argc, char *argv[]);
1784 } commands[] = {
1785         {"start", cmd_start},
1786         {"stop", cmd_stop},
1787         {"restart", cmd_restart},
1788         {"reload", cmd_reload},
1789         {"dump", cmd_dump},
1790         {"purge", cmd_purge},
1791         {"debug", cmd_debug},
1792         {"retry", cmd_retry},
1793         {"connect", cmd_connect},
1794         {"disconnect", cmd_disconnect},
1795         {"top", cmd_top},
1796         {"pcap", cmd_pcap},
1797         {"log", cmd_log},
1798         {"pid", cmd_pid},
1799         {"config", cmd_config},
1800         {"init", cmd_init},
1801         {"generate-keys", cmd_generate_keys},
1802         {"generate-rsa-keys", cmd_generate_rsa_keys},
1803         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1804         {"help", cmd_help},
1805         {"version", cmd_version},
1806         {"info", cmd_info},
1807         {"edit", cmd_edit},
1808         {"export", cmd_export},
1809         {"export-all", cmd_export_all},
1810         {"import", cmd_import},
1811         {NULL, NULL},
1812 };
1813
1814 #ifdef HAVE_READLINE
1815 static char *complete_command(const char *text, int state) {
1816         static int i;
1817
1818         if(!state)
1819                 i = 0;
1820         else
1821                 i++;
1822
1823         while(commands[i].command) {
1824                 if(!strncasecmp(commands[i].command, text, strlen(text)))
1825                         return xstrdup(commands[i].command);
1826                 i++;
1827         }
1828
1829         return NULL;
1830 }
1831
1832 static char *complete_dump(const char *text, int state) {
1833         const char *matches[] = {"nodes", "edges", "subnets", "connections", "graph", NULL};
1834         static int i;
1835
1836         if(!state)
1837                 i = 0;
1838         else
1839                 i++;
1840
1841         while(matches[i]) {
1842                 if(!strncasecmp(matches[i], text, strlen(text)))
1843                         return xstrdup(matches[i]);
1844                 i++;
1845         }
1846
1847         return NULL;
1848 }
1849
1850 static char *complete_config(const char *text, int state) {
1851         const char *sub[] = {"get", "set", "add", "del"};
1852         static int i;
1853         if(!state) {
1854                 i = 0;
1855                 if(!strchr(rl_line_buffer + 7, ' '))
1856                         i = -4;
1857                 else {
1858                         bool found = false;
1859                         for(int i = 0; i < 4; i++) {
1860                                 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1861                                         found = true;
1862                                         break;
1863                                 }
1864                         }
1865                         if(!found)
1866                                 return NULL;
1867                 }
1868         } else {
1869                 i++;
1870         }
1871
1872         while(i < 0 || variables[i].name) {
1873                 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
1874                         return xstrdup(sub[i + 4]);
1875                 if(i >= 0) {
1876                         char *dot = strchr(text, '.');
1877                         if(dot) {
1878                                 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
1879                                         char *match;
1880                                         xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
1881                                         return match;
1882                                 }
1883                         } else {
1884                                 if(!strncasecmp(variables[i].name, text, strlen(text)))
1885                                         return xstrdup(variables[i].name);
1886                         }
1887                 }
1888                 i++;
1889         }
1890
1891         return NULL;
1892 }
1893
1894 static char *complete_info(const char *text, int state) {
1895         static int i;
1896         if(!state) {
1897                 i = 0;
1898                 if(!connect_tincd(false))
1899                         return NULL;
1900                 // Check the list of nodes
1901                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
1902                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
1903         }
1904
1905         while(recvline(fd, line, sizeof line)) {
1906                 char item[4096];
1907                 int n = sscanf(line, "%d %d %s", &code, &req, item);
1908                 if(n == 2) {
1909                         i++;
1910                         if(i >= 2)
1911                                 break;
1912                         else
1913                                 continue;
1914                 }
1915
1916                 if(n != 3) {
1917                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
1918                         break;
1919                 }
1920
1921                 if(!strncmp(item, text, strlen(text)))
1922                         return xstrdup(strip_weight(item));
1923         }
1924
1925         return NULL;
1926 }
1927
1928 static char *complete_nothing(const char *text, int state) {
1929         return NULL;
1930 }
1931
1932 static char **completion (const char *text, int start, int end) {
1933         char **matches = NULL;
1934
1935         if(!start)
1936                 matches = rl_completion_matches(text, complete_command);
1937         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
1938                 matches = rl_completion_matches(text, complete_dump);
1939         else if(!strncasecmp(rl_line_buffer, "config ", 7))
1940                 matches = rl_completion_matches(text, complete_config);
1941         else if(!strncasecmp(rl_line_buffer, "info ", 5))
1942                 matches = rl_completion_matches(text, complete_info);
1943
1944         return matches;
1945 }
1946 #endif
1947
1948 static int cmd_shell(int argc, char *argv[]) {
1949         char *prompt;
1950         xasprintf(&prompt, "%s> ", identname);
1951         int result = 0;
1952         char buf[4096];
1953         char *line = NULL;
1954         int maxargs = argc + 16;
1955         char **nargv = xmalloc(maxargs * sizeof *nargv);
1956         optind = argc;
1957
1958         for(int i = 0; i < argc; i++)
1959                 nargv[i] = argv[i];
1960
1961 #ifdef HAVE_READLINE
1962         rl_readline_name = "tinc";
1963         rl_completion_entry_function = complete_nothing;
1964         rl_attempted_completion_function = completion;
1965         rl_filename_completion_desired = 0;
1966         char *copy = NULL;
1967 #endif
1968
1969         while(true) {
1970 #ifdef HAVE_READLINE
1971                 if(tty) {
1972                         free(copy);
1973                         free(line);
1974                         rl_basic_word_break_characters = "\t\n ";
1975                         line = readline(prompt);
1976                         if(line)
1977                                 copy = xstrdup(line);
1978                 } else {
1979                         line = fgets(buf, sizeof buf, stdin);
1980                 }
1981 #else
1982                 if(tty)
1983                         fputs(prompt, stdout);
1984
1985                 line = fgets(buf, sizeof buf, stdin);
1986 #endif
1987
1988                 if(!line)
1989                         break;
1990
1991                 /* Ignore comments */
1992
1993                 if(*line == '#')
1994                         continue;
1995
1996                 /* Split */
1997
1998                 int nargc = argc;
1999                 char *p = line + strspn(line, " \t\n");
2000                 char *next = strtok(p, " \t\n");
2001
2002                 while(p && *p) {
2003                         if(nargc >= maxargs) {
2004                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2005                                 abort();
2006                                 maxargs *= 2;
2007                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2008                         }
2009
2010                         nargv[nargc++] = p;
2011                         p = next;
2012                         next = strtok(NULL, " \t\n");
2013                 }
2014
2015                 if(nargc == argc)
2016                         continue;
2017
2018                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2019                         return result;
2020
2021                 bool found = false;
2022
2023                 for(int i = 0; commands[i].command; i++) {
2024                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2025                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2026                                 found = true;
2027                                 break;
2028                         }
2029                 }
2030
2031 #ifdef HAVE_READLINE
2032                 if(tty && found)
2033                         add_history(copy);
2034 #endif
2035
2036                 if(!found) {
2037                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2038                         result |= 1;
2039                 }
2040         }
2041
2042         if(tty)
2043                 printf("\n");
2044         return result;
2045 }
2046
2047
2048 int main(int argc, char *argv[]) {
2049         program_name = argv[0];
2050         orig_argv = argv;
2051         orig_argc = argc;
2052
2053         if(!parse_options(argc, argv))
2054                 return 1;
2055         
2056         make_names();
2057
2058         if(show_version) {
2059                 version();
2060                 return 0;
2061         }
2062
2063         if(show_help) {
2064                 usage(false);
2065                 return 0;
2066         }
2067
2068         tty = isatty(0) && isatty(1);
2069
2070         if(optind >= argc)
2071                 return cmd_shell(argc, argv);
2072
2073         for(int i = 0; commands[i].command; i++) {
2074                 if(!strcasecmp(argv[optind], commands[i].command))
2075                         return commands[i].function(argc - optind, argv + optind);
2076         }
2077
2078         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2079         usage(true);
2080         return 1;
2081 }