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