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