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