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