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