Don't complain about garbage if we skipped importing a host file.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2012 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <getopt.h>
23
24 #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 #ifndef HAVE_MINGW
858         if(!connect_tincd(true)) {
859                 if(pid) {
860                         if(kill(pid, SIGTERM)) {
861                                 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
862                                 return 1;
863                         }
864
865                         fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
866                         waitpid(pid, NULL, 0);
867                         return 0;
868                 }
869
870                 return 1;
871         }
872
873         sendline(fd, "%d %d", CONTROL, REQ_STOP);
874         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
875                 fprintf(stderr, "Could not stop tinc daemon.\n");
876                 return 1;
877         }
878
879         // Wait for tincd to close the connection...
880         fd_set r;
881         FD_ZERO(&r);
882         FD_SET(fd, &r);
883         select(fd + 1, &r, NULL, NULL, NULL);
884 #else
885         if(!remove_service())
886                 return 1;
887 #endif
888         close(fd);
889         pid = 0;
890         fd = -1;
891
892         return 0;
893 }
894
895 static int cmd_restart(int argc, char *argv[]) {
896         cmd_stop(argc, argv);
897         return cmd_start(argc, argv);
898 }
899
900 static int cmd_reload(int argc, char *argv[]) {
901         if(!connect_tincd(true))
902                 return 1;
903
904         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
905         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
906                 fprintf(stderr, "Could not reload configuration.\n");
907                 return 1;
908         }
909
910         return 0;
911
912 }
913
914 static int cmd_dump(int argc, char *argv[]) {
915         bool only_reachable = false;
916
917         if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
918                 if(strcasecmp(argv[2], "nodes")) {
919                         fprintf(stderr, "`reachable' only supported for nodes.\n");
920                         usage(true);
921                         return 1;
922                 }
923                 only_reachable = true;
924                 argv++;
925                 argc--;
926         }
927
928         if(argc != 2) {
929                 fprintf(stderr, "Invalid number of arguments.\n");
930                 usage(true);
931                 return 1;
932         }
933
934         if(!connect_tincd(true))
935                 return 1;
936
937         int do_graph = 0;
938
939         if(!strcasecmp(argv[1], "nodes"))
940                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
941         else if(!strcasecmp(argv[1], "edges"))
942                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
943         else if(!strcasecmp(argv[1], "subnets"))
944                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
945         else if(!strcasecmp(argv[1], "connections"))
946                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
947         else if(!strcasecmp(argv[1], "graph")) {
948                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
949                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
950                 do_graph = 1;
951         } else if(!strcasecmp(argv[1], "digraph")) {
952                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
953                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
954                 do_graph = 2;
955         } else {
956                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
957                 usage(true);
958                 return 1;
959         }
960
961         if(do_graph == 1)
962                 printf("graph {\n");
963         else if(do_graph == 2)
964                 printf("digraph {\n");
965
966         while(recvline(fd, line, sizeof line)) {
967                 char node1[4096], node2[4096];
968                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
969                 if(n == 2) {
970                         if(do_graph && req == REQ_DUMP_NODES)
971                                 continue;
972                         else {
973                                 if(do_graph)
974                                         printf("}\n");
975                                 return 0;
976                         }
977                 }
978                 if(n < 2)
979                         break;
980
981                 char node[4096];
982                 char from[4096];
983                 char to[4096];
984                 char subnet[4096];
985                 char host[4096];
986                 char port[4096];
987                 char via[4096];
988                 char nexthop[4096];
989                 int cipher, digest, maclength, compression, distance, socket, weight;
990                 short int pmtu, minmtu, maxmtu;
991                 unsigned int options, status_int;
992                 node_status_t status;
993                 long int last_state_change;
994
995                 switch(req) {
996                         case REQ_DUMP_NODES: {
997                                 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);
998                                 if(n != 16) {
999                                         fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1000                                         return 1;
1001                                 }
1002
1003                                 memcpy(&status, &status_int, sizeof status);
1004
1005                                 if(do_graph) {
1006                                         const char *color = "black";
1007                                         if(!strcmp(host, "MYSELF"))
1008                                                 color = "green";
1009                                         else if(!status.reachable)
1010                                                 color = "red";
1011                                         else if(strcmp(via, node))
1012                                                 color = "orange";
1013                                         else if(!status.validkey)
1014                                                 color = "black";
1015                                         else if(minmtu > 0)
1016                                                 color = "green";
1017                                         printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1018                                 } else {
1019                                         if(only_reachable && !status.reachable)
1020                                                 continue;
1021                                         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",
1022                                                         node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1023                                 }
1024                         } break;
1025
1026                         case REQ_DUMP_EDGES: {
1027                                 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1028                                 if(n != 6) {
1029                                         fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1030                                         return 1;
1031                                 }
1032
1033                                 if(do_graph) {
1034                                         float w = 1 + 65536.0 / weight;
1035                                         if(do_graph == 1 && strcmp(node1, node2) > 0)
1036                                                 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1037                                         else if(do_graph == 2)
1038                                                 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1039                                 } else {
1040                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1041                                 }
1042                         } break;
1043
1044                         case REQ_DUMP_SUBNETS: {
1045                                 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1046                                 if(n != 2) {
1047                                         fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1048                                         return 1;
1049                                 }
1050                                 printf("%s owner %s\n", strip_weight(subnet), node);
1051                         } break;
1052
1053                         case REQ_DUMP_CONNECTIONS: {
1054                                 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1055                                 if(n != 6) {
1056                                         fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1057                                         return 1;
1058                                 }
1059                                 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1060                         } break;
1061
1062                         default:
1063                                 fprintf(stderr, "Unable to parse dump from tincd.\n");
1064                                 return 1;
1065                 }
1066         }
1067
1068         fprintf(stderr, "Error receiving dump.\n");
1069         return 1;
1070 }
1071
1072 static int cmd_purge(int argc, char *argv[]) {
1073         if(!connect_tincd(true))
1074                 return 1;
1075
1076         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1077         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1078                 fprintf(stderr, "Could not purge old information.\n");
1079                 return 1;
1080         }
1081
1082         return 0;
1083 }
1084
1085 static int cmd_debug(int argc, char *argv[]) {
1086         if(argc != 2) {
1087                 fprintf(stderr, "Invalid number of arguments.\n");
1088                 return 1;
1089         }
1090
1091         if(!connect_tincd(true))
1092                 return 1;
1093
1094         int debuglevel = atoi(argv[1]);
1095         int origlevel;
1096
1097         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1098         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1099                 fprintf(stderr, "Could not set debug level.\n");
1100                 return 1;
1101         }
1102
1103         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1104         return 0;
1105 }
1106
1107 static int cmd_retry(int argc, char *argv[]) {
1108         if(!connect_tincd(true))
1109                 return 1;
1110
1111         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1112         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1113                 fprintf(stderr, "Could not retry outgoing connections.\n");
1114                 return 1;
1115         }
1116
1117         return 0;
1118 }
1119
1120 static int cmd_connect(int argc, char *argv[]) {
1121         if(argc != 2) {
1122                 fprintf(stderr, "Invalid number of arguments.\n");
1123                 return 1;
1124         }
1125
1126         if(!check_id(argv[1])) {
1127                 fprintf(stderr, "Invalid name for node.\n");
1128                 return 1;
1129         }
1130
1131         if(!connect_tincd(true))
1132                 return 1;
1133
1134         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1135         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1136                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1137                 return 1;
1138         }
1139
1140         return 0;
1141 }
1142
1143 static int cmd_disconnect(int argc, char *argv[]) {
1144         if(argc != 2) {
1145                 fprintf(stderr, "Invalid number of arguments.\n");
1146                 return 1;
1147         }
1148
1149         if(!check_id(argv[1])) {
1150                 fprintf(stderr, "Invalid name for node.\n");
1151                 return 1;
1152         }
1153
1154         if(!connect_tincd(true))
1155                 return 1;
1156
1157         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1158         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1159                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1160                 return 1;
1161         }
1162
1163         return 0;
1164 }
1165
1166 static int cmd_top(int argc, char *argv[]) {
1167 #ifdef HAVE_CURSES
1168         if(!connect_tincd(true))
1169                 return 1;
1170
1171         top(fd);
1172         return 0;
1173 #else
1174         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1175         return 1;
1176 #endif
1177 }
1178
1179 static int cmd_pcap(int argc, char *argv[]) {
1180         if(!connect_tincd(true))
1181                 return 1;
1182
1183         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1184         return 0;
1185 }
1186
1187 static int cmd_log(int argc, char *argv[]) {
1188         if(!connect_tincd(true))
1189                 return 1;
1190
1191         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1192         return 0;
1193 }
1194
1195 static int cmd_pid(int argc, char *argv[]) {
1196         if(!connect_tincd(true) && !pid)
1197                 return 1;
1198
1199         printf("%d\n", pid);
1200         return 0;
1201 }
1202
1203 static int rstrip(char *value) {
1204         int len = strlen(value);
1205         while(len && strchr("\t\r\n ", value[len - 1]))
1206                 value[--len] = 0;
1207         return len;
1208 }
1209
1210 static char *get_my_name() {
1211         FILE *f = fopen(tinc_conf, "r");
1212         if(!f) {
1213                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1214                 return NULL;
1215         }
1216
1217         char buf[4096];
1218         char *value;
1219         while(fgets(buf, sizeof buf, f)) {
1220                 int len = strcspn(buf, "\t =");
1221                 value = buf + len;
1222                 value += strspn(value, "\t ");
1223                 if(*value == '=') {
1224                         value++;
1225                         value += strspn(value, "\t ");
1226                 }
1227                 if(!rstrip(value))
1228                         continue;
1229                 buf[len] = 0;
1230                 if(strcasecmp(buf, "Name"))
1231                         continue;
1232                 if(*value) {
1233                         fclose(f);
1234                         return strdup(value);
1235                 }
1236         }
1237
1238         fclose(f);
1239         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1240         return NULL;
1241 }
1242
1243 #define VAR_SERVER 1    /* Should be in tinc.conf */
1244 #define VAR_HOST 2      /* Can be in host config file */
1245 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
1246 #define VAR_OBSOLETE 8  /* Should not be used anymore */
1247
1248 static struct {
1249         const char *name;
1250         int type;
1251 } const variables[] = {
1252         /* Server configuration */
1253         {"AddressFamily", VAR_SERVER},
1254         {"AutoConnect", VAR_SERVER},
1255         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1256         {"BindToInterface", VAR_SERVER},
1257         {"Broadcast", VAR_SERVER},
1258         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1259         {"DecrementTTL", VAR_SERVER},
1260         {"Device", VAR_SERVER},
1261         {"DeviceType", VAR_SERVER},
1262         {"DirectOnly", VAR_SERVER},
1263         {"ECDSAPrivateKeyFile", VAR_SERVER},
1264         {"ExperimentalProtocol", VAR_SERVER},
1265         {"Forwarding", VAR_SERVER},
1266         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1267         {"Hostnames", VAR_SERVER},
1268         {"IffOneQueue", VAR_SERVER},
1269         {"Interface", VAR_SERVER},
1270         {"KeyExpire", VAR_SERVER},
1271         {"LocalDiscovery", VAR_SERVER},
1272         {"MACExpire", VAR_SERVER},
1273         {"MaxOutputBufferSize", VAR_SERVER},
1274         {"MaxTimeout", VAR_SERVER},
1275         {"Mode", VAR_SERVER},
1276         {"Name", VAR_SERVER},
1277         {"PingInterval", VAR_SERVER},
1278         {"PingTimeout", VAR_SERVER},
1279         {"PriorityInheritance", VAR_SERVER},
1280         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1281         {"PrivateKeyFile", VAR_SERVER},
1282         {"ProcessPriority", VAR_SERVER},
1283         {"Proxy", VAR_SERVER},
1284         {"ReplayWindow", VAR_SERVER},
1285         {"ScriptsExtension", VAR_SERVER},
1286         {"ScriptsInterpreter", VAR_SERVER},
1287         {"StrictSubnets", VAR_SERVER},
1288         {"TunnelServer", VAR_SERVER},
1289         {"UDPRcvBuf", VAR_SERVER},
1290         {"UDPSndBuf", VAR_SERVER},
1291         {"VDEGroup", VAR_SERVER},
1292         {"VDEPort", VAR_SERVER},
1293         /* Host configuration */
1294         {"Address", VAR_HOST | VAR_MULTIPLE},
1295         {"Cipher", VAR_SERVER | VAR_HOST},
1296         {"ClampMSS", VAR_SERVER | VAR_HOST},
1297         {"Compression", VAR_SERVER | VAR_HOST},
1298         {"Digest", VAR_SERVER | VAR_HOST},
1299         {"ECDSAPublicKey", VAR_HOST},
1300         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1301         {"IndirectData", VAR_SERVER | VAR_HOST},
1302         {"MACLength", VAR_SERVER | VAR_HOST},
1303         {"PMTU", VAR_SERVER | VAR_HOST},
1304         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1305         {"Port", VAR_HOST},
1306         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1307         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1308         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1309         {"TCPOnly", VAR_SERVER | VAR_HOST},
1310         {"Weight", VAR_HOST},
1311         {NULL, 0}
1312 };
1313
1314 static int cmd_config(int argc, char *argv[]) {
1315         if(argc < 2) {
1316                 fprintf(stderr, "Invalid number of arguments.\n");
1317                 return 1;
1318         }
1319
1320         int action = -2;
1321         if(!strcasecmp(argv[1], "get")) {
1322                 argv++, argc--;
1323         } else if(!strcasecmp(argv[1], "add")) {
1324                 argv++, argc--, action = 1;
1325         } else if(!strcasecmp(argv[1], "del")) {
1326                 argv++, argc--, action = -1;
1327         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1328                 argv++, argc--, action = 0;
1329         }
1330
1331         if(argc < 2) {
1332                 fprintf(stderr, "Invalid number of arguments.\n");
1333                 return 1;
1334         }
1335
1336         // Concatenate the rest of the command line
1337         strncpy(line, argv[1], sizeof line - 1);
1338         for(int i = 2; i < argc; i++) {
1339                 strncat(line, " ", sizeof line - 1 - strlen(line));
1340                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1341         }
1342
1343         // Liberal parsing into node name, variable name and value.
1344         char *node = NULL;
1345         char *variable;
1346         char *value;
1347         int len;
1348
1349         len = strcspn(line, "\t =");
1350         value = line + len;
1351         value += strspn(value, "\t ");
1352         if(*value == '=') {
1353                 value++;
1354                 value += strspn(value, "\t ");
1355         }
1356         line[len] = '\0';
1357         variable = strchr(line, '.');
1358         if(variable) {
1359                 node = line;
1360                 *variable++ = 0;
1361         } else {
1362                 variable = line;
1363         }
1364
1365         if(!*variable) {
1366                 fprintf(stderr, "No variable given.\n");
1367                 return 1;
1368         }
1369
1370         if(action >= 0 && !*value) {
1371                 fprintf(stderr, "No value for variable given.\n");
1372                 return 1;
1373         }
1374
1375         if(action < -1 && *value)
1376                 action = 0;
1377
1378         /* Some simple checks. */
1379         bool found = false;
1380
1381         for(int i = 0; variables[i].name; i++) {
1382                 if(strcasecmp(variables[i].name, variable))
1383                         continue;
1384
1385                 found = true;
1386                 variable = (char *)variables[i].name;
1387
1388                 /* Discourage use of obsolete variables. */
1389
1390                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1391                         if(force) {
1392                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1393                         } else {
1394                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1395                                 return 1;
1396                         }
1397                 }
1398
1399                 /* Don't put server variables in host config files */
1400
1401                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1402                         if(force) {
1403                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1404                         } else {
1405                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1406                                 return 1;
1407                         }
1408                 }
1409
1410                 /* Should this go into our own host config file? */
1411
1412                 if(!node && !(variables[i].type & VAR_SERVER)) {
1413                         node = get_my_name();
1414                         if(!node)
1415                                 return 1;
1416                 }
1417
1418                 break;
1419         }
1420
1421         if(node && !check_id(node)) {
1422                 fprintf(stderr, "Invalid name for node.\n");
1423                 return 1;
1424         }
1425
1426         if(!found) {
1427                 if(force || action < 0) {
1428                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1429                 } else {
1430                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1431                         return 1;
1432                 }
1433         }
1434
1435         // Open the right configuration file.
1436         char *filename;
1437         if(node)
1438                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1439         else
1440                 filename = tinc_conf;
1441
1442         FILE *f = fopen(filename, "r");
1443         if(!f) {
1444                 if(action < 0 || errno != ENOENT) {
1445                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1446                         return 1;
1447                 }
1448
1449                 // If it doesn't exist, create it.
1450                 f = fopen(filename, "a+");
1451                 if(!f) {
1452                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1453                         return 1;
1454                 } else {
1455                         fprintf(stderr, "Created configuration file %s.\n", filename);
1456                 }
1457         }
1458
1459         char *tmpfile = NULL;
1460         FILE *tf = NULL;
1461
1462         if(action >= -1) {
1463                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1464                 tf = fopen(tmpfile, "w");
1465                 if(!tf) {
1466                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1467                         fclose(f);
1468                         return 1;
1469                 }
1470         }
1471
1472         // Copy the file, making modifications on the fly, unless we are just getting a value.
1473         char buf1[4096];
1474         char buf2[4096];
1475         bool set = false;
1476         bool removed = false;
1477         found = false;
1478
1479         while(fgets(buf1, sizeof buf1, f)) {
1480                 buf1[sizeof buf1 - 1] = 0;
1481                 strncpy(buf2, buf1, sizeof buf2);
1482
1483                 // Parse line in a simple way
1484                 char *bvalue;
1485                 int len;
1486
1487                 len = strcspn(buf2, "\t =");
1488                 bvalue = buf2 + len;
1489                 bvalue += strspn(bvalue, "\t ");
1490                 if(*bvalue == '=') {
1491                         bvalue++;
1492                         bvalue += strspn(bvalue, "\t ");
1493                 }
1494                 rstrip(bvalue);
1495                 buf2[len] = '\0';
1496
1497                 // Did it match?
1498                 if(!strcasecmp(buf2, variable)) {
1499                         // Get
1500                         if(action < -1) {
1501                                 found = true;
1502                                 printf("%s\n", bvalue);
1503                         // Del
1504                         } else if(action == -1) {
1505                                 if(!*value || !strcasecmp(bvalue, value)) {
1506                                         removed = true;
1507                                         continue;
1508                                 }
1509                         // Set
1510                         } else if(action == 0) {
1511                                 // Already set? Delete the rest...
1512                                 if(set)
1513                                         continue;
1514                                 // Otherwise, replace.
1515                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1516                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1517                                         return 1;
1518                                 }
1519                                 set = true;
1520                                 continue;
1521                         }
1522                 }
1523
1524                 if(action >= -1) {
1525                         // Copy original line...
1526                         if(fputs(buf1, tf) < 0) {
1527                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1528                                 return 1;
1529                         }
1530
1531                         // Add newline if it is missing...
1532                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1533                                 if(fputc('\n', tf) < 0) {
1534                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1535                                         return 1;
1536                                 }
1537                         }
1538                 }
1539         }
1540
1541         // Make sure we read everything...
1542         if(ferror(f) || !feof(f)) {
1543                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1544                 return 1;
1545         }
1546
1547         if(fclose(f)) {
1548                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1549                 return 1;
1550         }
1551
1552         // Add new variable if necessary.
1553         if(action > 0 || (action == 0 && !set)) {
1554                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1555                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1556                         return 1;
1557                 }
1558         }
1559
1560         if(action < -1) {
1561                 if(!found)
1562                         fprintf(stderr, "No matching configuration variables found.\n");
1563                 return 0;
1564         }
1565
1566         // Make sure we wrote everything...
1567         if(fclose(tf)) {
1568                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1569                 return 1;
1570         }
1571
1572         // Could we find what we had to remove?
1573         if(action < 0 && !removed) {
1574                 remove(tmpfile);
1575                 fprintf(stderr, "No configuration variables deleted.\n");
1576                 return *value;
1577         }
1578
1579         // Replace the configuration file with the new one
1580 #ifdef HAVE_MINGW
1581         if(remove(filename)) {
1582                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1583                 return 1;
1584         }
1585 #endif
1586         if(rename(tmpfile, filename)) {
1587                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1588                 return 1;
1589         }
1590
1591         // Silently try notifying a running tincd of changes.
1592         if(connect_tincd(false))
1593                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1594
1595         return 0;
1596 }
1597
1598 bool check_id(const char *name) {
1599         if(!name || !*name)
1600                 return false;
1601
1602         for(int i = 0; i < strlen(name); i++) {
1603                 if(!isalnum(name[i]) && name[i] != '_')
1604                         return false;
1605         }
1606
1607         return true;
1608 }
1609
1610 static int cmd_init(int argc, char *argv[]) {
1611         if(!access(tinc_conf, F_OK)) {
1612                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1613                 return 1;
1614         }
1615
1616         if(argc < 2) {
1617                 if(tty) {
1618                         char buf[1024];
1619                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1620                         fflush(stdout);
1621                         if(!fgets(buf, sizeof buf, stdin)) {
1622                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1623                                 return 1;
1624                         }
1625                         int len = rstrip(buf);
1626                         if(!len) {
1627                                 fprintf(stderr, "No name given!\n");
1628                                 return 1;
1629                         }
1630                         name = strdup(buf);
1631                 } else {
1632                         fprintf(stderr, "No Name given!\n");
1633                         return 1;
1634                 }
1635         } else {
1636                 name = strdup(argv[1]);
1637                 if(!*name) {
1638                         fprintf(stderr, "No Name given!\n");
1639                         return 1;
1640                 }
1641         }
1642
1643         if(!check_id(name)) {
1644                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1645                 return 1;
1646         }
1647
1648         if(mkdir(confdir, 0755) && errno != EEXIST) {
1649                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1650                 return 1;
1651         }
1652
1653         if(mkdir(confbase, 0755) && errno != EEXIST) {
1654                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1655                 return 1;
1656         }
1657
1658         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1659                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1660                 return 1;
1661         }
1662
1663         FILE *f = fopen(tinc_conf, "w");
1664         if(!f) {
1665                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1666                 return 1;
1667         }
1668
1669         fprintf(f, "Name = %s\n", name);
1670         fclose(f);
1671
1672         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1673                 return 1;
1674
1675 #ifndef HAVE_MINGW
1676         char *filename;
1677         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1678         if(access(filename, F_OK)) {
1679                 FILE *f = fopen(filename, "w");
1680                 if(!f) {
1681                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1682                         return 1;
1683                 }
1684                 fchmod(fileno(f), 0755);
1685                 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");
1686                 fclose(f);
1687         }
1688 #endif
1689
1690         return 0;
1691
1692 }
1693
1694 static int cmd_generate_keys(int argc, char *argv[]) {
1695         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1696 }
1697
1698 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1699         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1700 }
1701
1702 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1703         return !ecdsa_keygen(true);
1704 }
1705
1706 static int cmd_help(int argc, char *argv[]) {
1707         usage(false);
1708         return 0;
1709 }
1710
1711 static int cmd_version(int argc, char *argv[]) {
1712         version();
1713         return 0;
1714 }
1715
1716 static int cmd_info(int argc, char *argv[]) {
1717         if(argc != 2) {
1718                 fprintf(stderr, "Invalid number of arguments.\n");
1719                 return 1;
1720         }
1721
1722         if(!connect_tincd(true))
1723                 return 1;
1724
1725         return info(fd, argv[1]);
1726 }
1727
1728 static const char *conffiles[] = {
1729         "tinc.conf",
1730         "tinc-up",
1731         "tinc-down",
1732         "subnet-up",
1733         "subnet-down",
1734         "host-up",
1735         "host-down",
1736         NULL,
1737 };
1738
1739 static int cmd_edit(int argc, char *argv[]) {
1740         if(argc != 2) {
1741                 fprintf(stderr, "Invalid number of arguments.\n");
1742                 return 1;
1743         }
1744
1745         char *filename = NULL;
1746
1747         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1748                 for(int i = 0; conffiles[i]; i++) {
1749                         if(!strcmp(argv[1], conffiles[i])) {
1750                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1751                                 break;
1752                         }
1753                 }
1754         } else {
1755                 argv[1] += 6;
1756         }
1757
1758         if(!filename) {
1759                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1760                 char *dash = strchr(argv[1], '-');
1761                 if(dash) {
1762                         *dash++ = 0;
1763                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1764                                 fprintf(stderr, "Invalid configuration filename.\n");
1765                                 return 1;
1766                         }
1767                 }
1768         }
1769
1770         char *command;
1771 #ifndef HAVE_MINGW
1772         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1773 #else
1774         xasprintf(&command, "edit \"%s\"", filename);
1775 #endif
1776         int result = system(command);
1777         if(result)
1778                 return result;
1779
1780         // Silently try notifying a running tincd of changes.
1781         if(connect_tincd(false))
1782                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1783
1784         return 0;
1785 }
1786
1787 static int export(const char *name, FILE *out) {
1788         char *filename;
1789         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1790         FILE *in = fopen(filename, "r");
1791         if(!in) {
1792                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1793                 return 1;
1794         }
1795
1796         fprintf(out, "Name = %s\n", name);
1797         char buf[4096];
1798         while(fgets(buf, sizeof buf, in)) {
1799                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1800                         fputs(buf, out);
1801         }
1802
1803         if(ferror(in)) {
1804                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1805                 fclose(in);
1806                 return 1;
1807         }
1808
1809         fclose(in);
1810         return 0;
1811 }
1812
1813 static int cmd_export(int argc, char *argv[]) {
1814         char *name = get_my_name();
1815         if(!name)
1816                 return 1;
1817
1818         return export(name, stdout);
1819 }
1820
1821 static int cmd_export_all(int argc, char *argv[]) {
1822         DIR *dir = opendir(hosts_dir);
1823         if(!dir) {
1824                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1825                 return 1;
1826         }
1827
1828         bool first = true;
1829         int result = 0;
1830         struct dirent *ent;
1831
1832         while((ent = readdir(dir))) {
1833                 if(!check_id(ent->d_name))
1834                         continue;
1835
1836                 if(first)
1837                         first = false;
1838                 else
1839                         printf("#---------------------------------------------------------------#\n");
1840
1841                 result |= export(ent->d_name, stdout);
1842         }
1843
1844         closedir(dir);
1845         return result;
1846 }
1847
1848 static int cmd_import(int argc, char *argv[]) {
1849         FILE *in = stdin;
1850         FILE *out = NULL;
1851
1852         char buf[4096];
1853         char name[4096];
1854         char *filename;
1855         int count = 0;
1856         bool firstline = true;
1857
1858         while(fgets(buf, sizeof buf, in)) {
1859                 if(sscanf(buf, "Name = %s", name) == 1) {
1860                         firstline = false;
1861
1862                         if(!check_id(name)) {
1863                                 fprintf(stderr, "Invalid Name in input!\n");
1864                                 return 1;
1865                         }
1866
1867                         if(out)
1868                                 fclose(out);
1869
1870                         free(filename);
1871                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1872
1873                         if(!force && !access(filename, F_OK)) {
1874                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1875                                 out = NULL;
1876                                 continue;
1877                         }
1878
1879                         out = fopen(filename, "w");
1880                         if(!out) {
1881                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1882                                 return 1;
1883                         }
1884
1885                         count++;
1886                         continue;
1887                 } else if(firstline) {
1888                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1889                         firstline = false;
1890                 }
1891
1892
1893                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1894                         continue;
1895
1896                 if(out) {
1897                         if(fputs(buf, out) < 0) {
1898                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1899                                 return 1;
1900                         }
1901                 }
1902         }
1903
1904         if(out)
1905                 fclose(out);
1906
1907         if(count) {
1908                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1909                 return 0;
1910         } else {
1911                 fprintf(stderr, "No host configuration files imported.\n");
1912                 return 1;
1913         }
1914 }
1915
1916 static const struct {
1917         const char *command;
1918         int (*function)(int argc, char *argv[]);
1919 } commands[] = {
1920         {"start", cmd_start},
1921         {"stop", cmd_stop},
1922         {"restart", cmd_restart},
1923         {"reload", cmd_reload},
1924         {"dump", cmd_dump},
1925         {"purge", cmd_purge},
1926         {"debug", cmd_debug},
1927         {"retry", cmd_retry},
1928         {"connect", cmd_connect},
1929         {"disconnect", cmd_disconnect},
1930         {"top", cmd_top},
1931         {"pcap", cmd_pcap},
1932         {"log", cmd_log},
1933         {"pid", cmd_pid},
1934         {"config", cmd_config},
1935         {"init", cmd_init},
1936         {"generate-keys", cmd_generate_keys},
1937         {"generate-rsa-keys", cmd_generate_rsa_keys},
1938         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1939         {"help", cmd_help},
1940         {"version", cmd_version},
1941         {"info", cmd_info},
1942         {"edit", cmd_edit},
1943         {"export", cmd_export},
1944         {"export-all", cmd_export_all},
1945         {"import", cmd_import},
1946         {NULL, NULL},
1947 };
1948
1949 #ifdef HAVE_READLINE
1950 static char *complete_command(const char *text, int state) {
1951         static int i;
1952
1953         if(!state)
1954                 i = 0;
1955         else
1956                 i++;
1957
1958         while(commands[i].command) {
1959                 if(!strncasecmp(commands[i].command, text, strlen(text)))
1960                         return xstrdup(commands[i].command);
1961                 i++;
1962         }
1963
1964         return NULL;
1965 }
1966
1967 static char *complete_dump(const char *text, int state) {
1968         const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
1969         static int i;
1970
1971         if(!state)
1972                 i = 0;
1973         else
1974                 i++;
1975
1976         while(matches[i]) {
1977                 if(!strncasecmp(matches[i], text, strlen(text)))
1978                         return xstrdup(matches[i]);
1979                 i++;
1980         }
1981
1982         return NULL;
1983 }
1984
1985 static char *complete_config(const char *text, int state) {
1986         const char *sub[] = {"get", "set", "add", "del"};
1987         static int i;
1988         if(!state) {
1989                 i = 0;
1990                 if(!strchr(rl_line_buffer + 7, ' '))
1991                         i = -4;
1992                 else {
1993                         bool found = false;
1994                         for(int i = 0; i < 4; i++) {
1995                                 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
1996                                         found = true;
1997                                         break;
1998                                 }
1999                         }
2000                         if(!found)
2001                                 return NULL;
2002                 }
2003         } else {
2004                 i++;
2005         }
2006
2007         while(i < 0 || variables[i].name) {
2008                 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2009                         return xstrdup(sub[i + 4]);
2010                 if(i >= 0) {
2011                         char *dot = strchr(text, '.');
2012                         if(dot) {
2013                                 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2014                                         char *match;
2015                                         xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2016                                         return match;
2017                                 }
2018                         } else {
2019                                 if(!strncasecmp(variables[i].name, text, strlen(text)))
2020                                         return xstrdup(variables[i].name);
2021                         }
2022                 }
2023                 i++;
2024         }
2025
2026         return NULL;
2027 }
2028
2029 static char *complete_info(const char *text, int state) {
2030         static int i;
2031         if(!state) {
2032                 i = 0;
2033                 if(!connect_tincd(false))
2034                         return NULL;
2035                 // Check the list of nodes
2036                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2037                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2038         }
2039
2040         while(recvline(fd, line, sizeof line)) {
2041                 char item[4096];
2042                 int n = sscanf(line, "%d %d %s", &code, &req, item);
2043                 if(n == 2) {
2044                         i++;
2045                         if(i >= 2)
2046                                 break;
2047                         else
2048                                 continue;
2049                 }
2050
2051                 if(n != 3) {
2052                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2053                         break;
2054                 }
2055
2056                 if(!strncmp(item, text, strlen(text)))
2057                         return xstrdup(strip_weight(item));
2058         }
2059
2060         return NULL;
2061 }
2062
2063 static char *complete_nothing(const char *text, int state) {
2064         return NULL;
2065 }
2066
2067 static char **completion (const char *text, int start, int end) {
2068         char **matches = NULL;
2069
2070         if(!start)
2071                 matches = rl_completion_matches(text, complete_command);
2072         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2073                 matches = rl_completion_matches(text, complete_dump);
2074         else if(!strncasecmp(rl_line_buffer, "config ", 7))
2075                 matches = rl_completion_matches(text, complete_config);
2076         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2077                 matches = rl_completion_matches(text, complete_info);
2078
2079         return matches;
2080 }
2081 #endif
2082
2083 static int cmd_shell(int argc, char *argv[]) {
2084         char *prompt;
2085         xasprintf(&prompt, "%s> ", identname);
2086         int result = 0;
2087         char buf[4096];
2088         char *line = NULL;
2089         int maxargs = argc + 16;
2090         char **nargv = xmalloc(maxargs * sizeof *nargv);
2091
2092         for(int i = 0; i < argc; i++)
2093                 nargv[i] = argv[i];
2094
2095 #ifdef HAVE_READLINE
2096         rl_readline_name = "tinc";
2097         rl_completion_entry_function = complete_nothing;
2098         rl_attempted_completion_function = completion;
2099         rl_filename_completion_desired = 0;
2100         char *copy = NULL;
2101 #endif
2102
2103         while(true) {
2104 #ifdef HAVE_READLINE
2105                 if(tty) {
2106                         free(copy);
2107                         free(line);
2108                         rl_basic_word_break_characters = "\t\n ";
2109                         line = readline(prompt);
2110                         if(line)
2111                                 copy = xstrdup(line);
2112                 } else {
2113                         line = fgets(buf, sizeof buf, stdin);
2114                 }
2115 #else
2116                 if(tty)
2117                         fputs(prompt, stdout);
2118
2119                 line = fgets(buf, sizeof buf, stdin);
2120 #endif
2121
2122                 if(!line)
2123                         break;
2124
2125                 /* Ignore comments */
2126
2127                 if(*line == '#')
2128                         continue;
2129
2130                 /* Split */
2131
2132                 int nargc = argc;
2133                 char *p = line + strspn(line, " \t\n");
2134                 char *next = strtok(p, " \t\n");
2135
2136                 while(p && *p) {
2137                         if(nargc >= maxargs) {
2138                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2139                                 abort();
2140                                 maxargs *= 2;
2141                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2142                         }
2143
2144                         nargv[nargc++] = p;
2145                         p = next;
2146                         next = strtok(NULL, " \t\n");
2147                 }
2148
2149                 if(nargc == argc)
2150                         continue;
2151
2152                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2153                         return result;
2154
2155                 bool found = false;
2156
2157                 for(int i = 0; commands[i].command; i++) {
2158                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2159                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2160                                 found = true;
2161                                 break;
2162                         }
2163                 }
2164
2165 #ifdef HAVE_READLINE
2166                 if(tty && found)
2167                         add_history(copy);
2168 #endif
2169
2170                 if(!found) {
2171                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2172                         result |= 1;
2173                 }
2174         }
2175
2176         free(nargv);
2177
2178         if(tty)
2179                 printf("\n");
2180         return result;
2181 }
2182
2183
2184 int main(int argc, char *argv[]) {
2185         program_name = argv[0];
2186         orig_argv = argv;
2187         orig_argc = argc;
2188
2189         if(!parse_options(argc, argv))
2190                 return 1;
2191
2192         make_names();
2193
2194         if(show_version) {
2195                 version();
2196                 return 0;
2197         }
2198
2199         if(show_help) {
2200                 usage(false);
2201                 return 0;
2202         }
2203
2204         tty = isatty(0) && isatty(1);
2205
2206         if(optind >= argc)
2207                 return cmd_shell(argc, argv);
2208
2209         for(int i = 0; commands[i].command; i++) {
2210                 if(!strcasecmp(argv[optind], commands[i].command))
2211                         return commands[i].function(argc - optind, argv + optind);
2212         }
2213
2214         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2215         usage(true);
2216         return 1;
2217 }