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