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