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