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