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