Choose a different Port when 655 isn't available when doing "tinc init".
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2013 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <getopt.h>
23
24 #ifdef HAVE_READLINE
25 #include "readline/readline.h"
26 #include "readline/history.h"
27 #endif
28
29 #include "xalloc.h"
30 #include "protocol.h"
31 #include "control_common.h"
32 #include "crypto.h"
33 #include "ecdsagen.h"
34 #include "info.h"
35 #include "invitation.h"
36 #include "names.h"
37 #include "rsagen.h"
38 #include "utils.h"
39 #include "tincctl.h"
40 #include "top.h"
41
42 #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, result;
834 #ifdef SIGINT
835         signal(SIGINT, SIG_IGN);
836 #endif
837         result = waitpid(pid, &status, 0);
838 #ifdef SIGINT
839         signal(SIGINT, SIG_DFL);
840 #endif
841
842         if(result != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
843                 fprintf(stderr, "Error starting %s\n", c);
844                 return 1;
845         }
846
847         return 0;
848 #endif
849 }
850
851 static int cmd_stop(int argc, char *argv[]) {
852         if(argc > 1) {
853                 fprintf(stderr, "Too many arguments!\n");
854                 return 1;
855         }
856
857 #ifndef HAVE_MINGW
858         if(!connect_tincd(true)) {
859                 if(pid) {
860                         if(kill(pid, SIGTERM)) {
861                                 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
862                                 return 1;
863                         }
864
865                         fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
866                         waitpid(pid, NULL, 0);
867                         return 0;
868                 }
869
870                 return 1;
871         }
872
873         sendline(fd, "%d %d", CONTROL, REQ_STOP);
874
875         while(recvline(fd, line, sizeof line)) {
876                 // Wait for tincd to close the connection...
877         }
878 #else
879         if(!remove_service())
880                 return 1;
881 #endif
882         close(fd);
883         pid = 0;
884         fd = -1;
885
886         return 0;
887 }
888
889 static int cmd_restart(int argc, char *argv[]) {
890         cmd_stop(1, argv);
891         return cmd_start(argc, argv);
892 }
893
894 static int cmd_reload(int argc, char *argv[]) {
895         if(argc > 1) {
896                 fprintf(stderr, "Too many arguments!\n");
897                 return 1;
898         }
899
900         if(!connect_tincd(true))
901                 return 1;
902
903         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
904         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
905                 fprintf(stderr, "Could not reload configuration.\n");
906                 return 1;
907         }
908
909         return 0;
910
911 }
912
913 static int cmd_dump(int argc, char *argv[]) {
914         bool only_reachable = false;
915
916         if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
917                 if(strcasecmp(argv[2], "nodes")) {
918                         fprintf(stderr, "`reachable' only supported for nodes.\n");
919                         usage(true);
920                         return 1;
921                 }
922                 only_reachable = true;
923                 argv++;
924                 argc--;
925         }
926
927         if(argc != 2) {
928                 fprintf(stderr, "Invalid number of arguments.\n");
929                 usage(true);
930                 return 1;
931         }
932
933         if(!connect_tincd(true))
934                 return 1;
935
936         int do_graph = 0;
937
938         if(!strcasecmp(argv[1], "nodes"))
939                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
940         else if(!strcasecmp(argv[1], "edges"))
941                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
942         else if(!strcasecmp(argv[1], "subnets"))
943                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
944         else if(!strcasecmp(argv[1], "connections"))
945                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
946         else if(!strcasecmp(argv[1], "graph")) {
947                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
948                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
949                 do_graph = 1;
950         } else if(!strcasecmp(argv[1], "digraph")) {
951                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
952                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
953                 do_graph = 2;
954         } else {
955                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
956                 usage(true);
957                 return 1;
958         }
959
960         if(do_graph == 1)
961                 printf("graph {\n");
962         else if(do_graph == 2)
963                 printf("digraph {\n");
964
965         while(recvline(fd, line, sizeof line)) {
966                 char node1[4096], node2[4096];
967                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
968                 if(n == 2) {
969                         if(do_graph && req == REQ_DUMP_NODES)
970                                 continue;
971                         else {
972                                 if(do_graph)
973                                         printf("}\n");
974                                 return 0;
975                         }
976                 }
977                 if(n < 2)
978                         break;
979
980                 char node[4096];
981                 char from[4096];
982                 char to[4096];
983                 char subnet[4096];
984                 char host[4096];
985                 char port[4096];
986                 char via[4096];
987                 char nexthop[4096];
988                 int cipher, digest, maclength, compression, distance, socket, weight;
989                 short int pmtu, minmtu, maxmtu;
990                 unsigned int options, status_int;
991                 node_status_t status;
992                 long int last_state_change;
993
994                 switch(req) {
995                         case REQ_DUMP_NODES: {
996                                 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);
997                                 if(n != 16) {
998                                         fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
999                                         return 1;
1000                                 }
1001
1002                                 memcpy(&status, &status_int, sizeof status);
1003
1004                                 if(do_graph) {
1005                                         const char *color = "black";
1006                                         if(!strcmp(host, "MYSELF"))
1007                                                 color = "green";
1008                                         else if(!status.reachable)
1009                                                 color = "red";
1010                                         else if(strcmp(via, node))
1011                                                 color = "orange";
1012                                         else if(!status.validkey)
1013                                                 color = "black";
1014                                         else if(minmtu > 0)
1015                                                 color = "green";
1016                                         printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1017                                 } else {
1018                                         if(only_reachable && !status.reachable)
1019                                                 continue;
1020                                         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",
1021                                                         node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1022                                 }
1023                         } break;
1024
1025                         case REQ_DUMP_EDGES: {
1026                                 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1027                                 if(n != 6) {
1028                                         fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1029                                         return 1;
1030                                 }
1031
1032                                 if(do_graph) {
1033                                         float w = 1 + 65536.0 / weight;
1034                                         if(do_graph == 1 && strcmp(node1, node2) > 0)
1035                                                 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1036                                         else if(do_graph == 2)
1037                                                 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1038                                 } else {
1039                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1040                                 }
1041                         } break;
1042
1043                         case REQ_DUMP_SUBNETS: {
1044                                 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1045                                 if(n != 2) {
1046                                         fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1047                                         return 1;
1048                                 }
1049                                 printf("%s owner %s\n", strip_weight(subnet), node);
1050                         } break;
1051
1052                         case REQ_DUMP_CONNECTIONS: {
1053                                 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1054                                 if(n != 6) {
1055                                         fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1056                                         return 1;
1057                                 }
1058                                 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1059                         } break;
1060
1061                         default:
1062                                 fprintf(stderr, "Unable to parse dump from tincd.\n");
1063                                 return 1;
1064                 }
1065         }
1066
1067         fprintf(stderr, "Error receiving dump.\n");
1068         return 1;
1069 }
1070
1071 static int cmd_purge(int argc, char *argv[]) {
1072         if(argc > 1) {
1073                 fprintf(stderr, "Too many arguments!\n");
1074                 return 1;
1075         }
1076
1077         if(!connect_tincd(true))
1078                 return 1;
1079
1080         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1081         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1082                 fprintf(stderr, "Could not purge old information.\n");
1083                 return 1;
1084         }
1085
1086         return 0;
1087 }
1088
1089 static int cmd_debug(int argc, char *argv[]) {
1090         if(argc != 2) {
1091                 fprintf(stderr, "Invalid number of arguments.\n");
1092                 return 1;
1093         }
1094
1095         if(!connect_tincd(true))
1096                 return 1;
1097
1098         int debuglevel = atoi(argv[1]);
1099         int origlevel;
1100
1101         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1102         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1103                 fprintf(stderr, "Could not set debug level.\n");
1104                 return 1;
1105         }
1106
1107         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1108         return 0;
1109 }
1110
1111 static int cmd_retry(int argc, char *argv[]) {
1112         if(argc > 1) {
1113                 fprintf(stderr, "Too many arguments!\n");
1114                 return 1;
1115         }
1116
1117         if(!connect_tincd(true))
1118                 return 1;
1119
1120         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1121         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1122                 fprintf(stderr, "Could not retry outgoing connections.\n");
1123                 return 1;
1124         }
1125
1126         return 0;
1127 }
1128
1129 static int cmd_connect(int argc, char *argv[]) {
1130         if(argc != 2) {
1131                 fprintf(stderr, "Invalid number of arguments.\n");
1132                 return 1;
1133         }
1134
1135         if(!check_id(argv[1])) {
1136                 fprintf(stderr, "Invalid name for node.\n");
1137                 return 1;
1138         }
1139
1140         if(!connect_tincd(true))
1141                 return 1;
1142
1143         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1144         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1145                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1146                 return 1;
1147         }
1148
1149         return 0;
1150 }
1151
1152 static int cmd_disconnect(int argc, char *argv[]) {
1153         if(argc != 2) {
1154                 fprintf(stderr, "Invalid number of arguments.\n");
1155                 return 1;
1156         }
1157
1158         if(!check_id(argv[1])) {
1159                 fprintf(stderr, "Invalid name for node.\n");
1160                 return 1;
1161         }
1162
1163         if(!connect_tincd(true))
1164                 return 1;
1165
1166         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1167         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1168                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1169                 return 1;
1170         }
1171
1172         return 0;
1173 }
1174
1175 static int cmd_top(int argc, char *argv[]) {
1176         if(argc > 1) {
1177                 fprintf(stderr, "Too many arguments!\n");
1178                 return 1;
1179         }
1180
1181 #ifdef HAVE_CURSES
1182         if(!connect_tincd(true))
1183                 return 1;
1184
1185         top(fd);
1186         return 0;
1187 #else
1188         fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1189         return 1;
1190 #endif
1191 }
1192
1193 static int cmd_pcap(int argc, char *argv[]) {
1194         if(argc > 2) {
1195                 fprintf(stderr, "Too many arguments!\n");
1196                 return 1;
1197         }
1198
1199         if(!connect_tincd(true))
1200                 return 1;
1201
1202         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1203         return 0;
1204 }
1205
1206 #ifdef SIGINT
1207 static void sigint_handler(int sig) {
1208         fprintf(stderr, "\n");
1209         shutdown(fd, SHUT_RDWR);
1210 }
1211 #endif
1212
1213 static int cmd_log(int argc, char *argv[]) {
1214         if(argc > 2) {
1215                 fprintf(stderr, "Too many arguments!\n");
1216                 return 1;
1217         }
1218
1219         if(!connect_tincd(true))
1220                 return 1;
1221
1222 #ifdef SIGINT
1223         signal(SIGINT, sigint_handler);
1224 #endif
1225
1226         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1227
1228 #ifdef SIGINT
1229         signal(SIGINT, SIG_DFL);
1230 #endif
1231
1232         close(fd);
1233         fd = -1;
1234         return 0;
1235 }
1236
1237 static int cmd_pid(int argc, char *argv[]) {
1238         if(argc > 1) {
1239                 fprintf(stderr, "Too many arguments!\n");
1240                 return 1;
1241         }
1242
1243         if(!connect_tincd(true) && !pid)
1244                 return 1;
1245
1246         printf("%d\n", pid);
1247         return 0;
1248 }
1249
1250 int rstrip(char *value) {
1251         int len = strlen(value);
1252         while(len && strchr("\t\r\n ", value[len - 1]))
1253                 value[--len] = 0;
1254         return len;
1255 }
1256
1257 char *get_my_name(bool verbose) {
1258         FILE *f = fopen(tinc_conf, "r");
1259         if(!f) {
1260                 if(verbose)
1261                         fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1262                 return NULL;
1263         }
1264
1265         char buf[4096];
1266         char *value;
1267         while(fgets(buf, sizeof buf, f)) {
1268                 int len = strcspn(buf, "\t =");
1269                 value = buf + len;
1270                 value += strspn(value, "\t ");
1271                 if(*value == '=') {
1272                         value++;
1273                         value += strspn(value, "\t ");
1274                 }
1275                 if(!rstrip(value))
1276                         continue;
1277                 buf[len] = 0;
1278                 if(strcasecmp(buf, "Name"))
1279                         continue;
1280                 if(*value) {
1281                         fclose(f);
1282                         return strdup(value);
1283                 }
1284         }
1285
1286         fclose(f);
1287         if(verbose)
1288                 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1289         return NULL;
1290 }
1291
1292 const var_t variables[] = {
1293         /* Server configuration */
1294         {"AddressFamily", VAR_SERVER},
1295         {"AutoConnect", VAR_SERVER | VAR_SAFE},
1296         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1297         {"BindToInterface", VAR_SERVER},
1298         {"Broadcast", VAR_SERVER | VAR_SAFE},
1299         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1300         {"DecrementTTL", VAR_SERVER},
1301         {"Device", VAR_SERVER},
1302         {"DeviceType", VAR_SERVER},
1303         {"DirectOnly", VAR_SERVER},
1304         {"ECDSAPrivateKeyFile", VAR_SERVER},
1305         {"ExperimentalProtocol", VAR_SERVER},
1306         {"Forwarding", VAR_SERVER},
1307         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1308         {"Hostnames", VAR_SERVER},
1309         {"IffOneQueue", VAR_SERVER},
1310         {"Interface", VAR_SERVER},
1311         {"KeyExpire", VAR_SERVER},
1312         {"LocalDiscovery", VAR_SERVER},
1313         {"MACExpire", VAR_SERVER},
1314         {"MaxConnectionBurst", VAR_SERVER},
1315         {"MaxOutputBufferSize", VAR_SERVER},
1316         {"MaxTimeout", VAR_SERVER},
1317         {"Mode", VAR_SERVER | VAR_SAFE},
1318         {"Name", VAR_SERVER},
1319         {"PingInterval", VAR_SERVER},
1320         {"PingTimeout", VAR_SERVER},
1321         {"PriorityInheritance", VAR_SERVER},
1322         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1323         {"PrivateKeyFile", VAR_SERVER},
1324         {"ProcessPriority", VAR_SERVER},
1325         {"Proxy", VAR_SERVER},
1326         {"ReplayWindow", VAR_SERVER},
1327         {"ScriptsExtension", VAR_SERVER},
1328         {"ScriptsInterpreter", VAR_SERVER},
1329         {"StrictSubnets", VAR_SERVER},
1330         {"TunnelServer", VAR_SERVER},
1331         {"UDPRcvBuf", VAR_SERVER},
1332         {"UDPSndBuf", VAR_SERVER},
1333         {"VDEGroup", VAR_SERVER},
1334         {"VDEPort", VAR_SERVER},
1335         /* Host configuration */
1336         {"Address", VAR_HOST | VAR_MULTIPLE},
1337         {"Cipher", VAR_SERVER | VAR_HOST},
1338         {"ClampMSS", VAR_SERVER | VAR_HOST},
1339         {"Compression", VAR_SERVER | VAR_HOST},
1340         {"Digest", VAR_SERVER | VAR_HOST},
1341         {"ECDSAPublicKey", VAR_HOST},
1342         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1343         {"IndirectData", VAR_SERVER | VAR_HOST},
1344         {"MACLength", VAR_SERVER | VAR_HOST},
1345         {"PMTU", VAR_SERVER | VAR_HOST},
1346         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1347         {"Port", VAR_HOST},
1348         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1349         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1350         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1351         {"TCPOnly", VAR_SERVER | VAR_HOST},
1352         {"Weight", VAR_HOST | VAR_SAFE},
1353         {NULL, 0}
1354 };
1355
1356 static int cmd_config(int argc, char *argv[]) {
1357         if(argc < 2) {
1358                 fprintf(stderr, "Invalid number of arguments.\n");
1359                 return 1;
1360         }
1361
1362         if(strcasecmp(argv[0], "config"))
1363                 argv--, argc++;
1364
1365         int action = -2;
1366         if(!strcasecmp(argv[1], "get")) {
1367                 argv++, argc--;
1368         } else if(!strcasecmp(argv[1], "add")) {
1369                 argv++, argc--, action = 1;
1370         } else if(!strcasecmp(argv[1], "del")) {
1371                 argv++, argc--, action = -1;
1372         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1373                 argv++, argc--, action = 0;
1374         }
1375
1376         if(argc < 2) {
1377                 fprintf(stderr, "Invalid number of arguments.\n");
1378                 return 1;
1379         }
1380
1381         // Concatenate the rest of the command line
1382         strncpy(line, argv[1], sizeof line - 1);
1383         for(int i = 2; i < argc; i++) {
1384                 strncat(line, " ", sizeof line - 1 - strlen(line));
1385                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1386         }
1387
1388         // Liberal parsing into node name, variable name and value.
1389         char *node = NULL;
1390         char *variable;
1391         char *value;
1392         int len;
1393
1394         len = strcspn(line, "\t =");
1395         value = line + len;
1396         value += strspn(value, "\t ");
1397         if(*value == '=') {
1398                 value++;
1399                 value += strspn(value, "\t ");
1400         }
1401         line[len] = '\0';
1402         variable = strchr(line, '.');
1403         if(variable) {
1404                 node = line;
1405                 *variable++ = 0;
1406         } else {
1407                 variable = line;
1408         }
1409
1410         if(!*variable) {
1411                 fprintf(stderr, "No variable given.\n");
1412                 return 1;
1413         }
1414
1415         if(action >= 0 && !*value) {
1416                 fprintf(stderr, "No value for variable given.\n");
1417                 return 1;
1418         }
1419
1420         if(action < -1 && *value)
1421                 action = 0;
1422
1423         /* Some simple checks. */
1424         bool found = false;
1425         bool warnonremove = false;
1426
1427         for(int i = 0; variables[i].name; i++) {
1428                 if(strcasecmp(variables[i].name, variable))
1429                         continue;
1430
1431                 found = true;
1432                 variable = (char *)variables[i].name;
1433
1434                 /* Discourage use of obsolete variables. */
1435
1436                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1437                         if(force) {
1438                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1439                         } else {
1440                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1441                                 return 1;
1442                         }
1443                 }
1444
1445                 /* Don't put server variables in host config files */
1446
1447                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1448                         if(force) {
1449                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1450                         } else {
1451                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1452                                 return 1;
1453                         }
1454                 }
1455
1456                 /* Should this go into our own host config file? */
1457
1458                 if(!node && !(variables[i].type & VAR_SERVER)) {
1459                         node = get_my_name(true);
1460                         if(!node)
1461                                 return 1;
1462                 }
1463
1464                 /* Change "add" into "set" for variables that do not allow multiple occurences.
1465                    Turn on warnings when it seems variables might be removed unintentionally. */
1466
1467                 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1468                         warnonremove = true;
1469                         action = 0;
1470                 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1471                         warnonremove = true;
1472                 }
1473
1474                 break;
1475         }
1476
1477         if(node && !check_id(node)) {
1478                 fprintf(stderr, "Invalid name for node.\n");
1479                 return 1;
1480         }
1481
1482         if(!found) {
1483                 if(force || action < 0) {
1484                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1485                 } else {
1486                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1487                         return 1;
1488                 }
1489         }
1490
1491         // Open the right configuration file.
1492         char *filename;
1493         if(node)
1494                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1495         else
1496                 filename = tinc_conf;
1497
1498         FILE *f = fopen(filename, "r");
1499         if(!f) {
1500                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1501                 return 1;
1502         }
1503
1504         char *tmpfile = NULL;
1505         FILE *tf = NULL;
1506
1507         if(action >= -1) {
1508                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1509                 tf = fopen(tmpfile, "w");
1510                 if(!tf) {
1511                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1512                         fclose(f);
1513                         return 1;
1514                 }
1515         }
1516
1517         // Copy the file, making modifications on the fly, unless we are just getting a value.
1518         char buf1[4096];
1519         char buf2[4096];
1520         bool set = false;
1521         bool removed = false;
1522         found = false;
1523
1524         while(fgets(buf1, sizeof buf1, f)) {
1525                 buf1[sizeof buf1 - 1] = 0;
1526                 strncpy(buf2, buf1, sizeof buf2);
1527
1528                 // Parse line in a simple way
1529                 char *bvalue;
1530                 int len;
1531
1532                 len = strcspn(buf2, "\t =");
1533                 bvalue = buf2 + len;
1534                 bvalue += strspn(bvalue, "\t ");
1535                 if(*bvalue == '=') {
1536                         bvalue++;
1537                         bvalue += strspn(bvalue, "\t ");
1538                 }
1539                 rstrip(bvalue);
1540                 buf2[len] = '\0';
1541
1542                 // Did it match?
1543                 if(!strcasecmp(buf2, variable)) {
1544                         // Get
1545                         if(action < -1) {
1546                                 found = true;
1547                                 printf("%s\n", bvalue);
1548                         // Del
1549                         } else if(action == -1) {
1550                                 if(!*value || !strcasecmp(bvalue, value)) {
1551                                         removed = true;
1552                                         continue;
1553                                 }
1554                         // Set
1555                         } else if(action == 0) {
1556                                 // Warn if "set" was used for variables that can occur multiple times
1557                                 if(warnonremove && strcasecmp(bvalue, value))
1558                                         fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1559
1560                                 // Already set? Delete the rest...
1561                                 if(set)
1562                                         continue;
1563
1564                                 // Otherwise, replace.
1565                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1566                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1567                                         return 1;
1568                                 }
1569                                 set = true;
1570                                 continue;
1571                         }
1572                 }
1573
1574                 if(action >= -1) {
1575                         // Copy original line...
1576                         if(fputs(buf1, tf) < 0) {
1577                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1578                                 return 1;
1579                         }
1580
1581                         // Add newline if it is missing...
1582                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1583                                 if(fputc('\n', tf) < 0) {
1584                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1585                                         return 1;
1586                                 }
1587                         }
1588                 }
1589         }
1590
1591         // Make sure we read everything...
1592         if(ferror(f) || !feof(f)) {
1593                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1594                 return 1;
1595         }
1596
1597         if(fclose(f)) {
1598                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1599                 return 1;
1600         }
1601
1602         // Add new variable if necessary.
1603         if(action > 0 || (action == 0 && !set)) {
1604                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1605                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1606                         return 1;
1607                 }
1608         }
1609
1610         if(action < -1) {
1611                 if(!found)
1612                         fprintf(stderr, "No matching configuration variables found.\n");
1613                 return 0;
1614         }
1615
1616         // Make sure we wrote everything...
1617         if(fclose(tf)) {
1618                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1619                 return 1;
1620         }
1621
1622         // Could we find what we had to remove?
1623         if(action < 0 && !removed) {
1624                 remove(tmpfile);
1625                 fprintf(stderr, "No configuration variables deleted.\n");
1626                 return *value;
1627         }
1628
1629         // Replace the configuration file with the new one
1630 #ifdef HAVE_MINGW
1631         if(remove(filename)) {
1632                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1633                 return 1;
1634         }
1635 #endif
1636         if(rename(tmpfile, filename)) {
1637                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1638                 return 1;
1639         }
1640
1641         // Silently try notifying a running tincd of changes.
1642         if(connect_tincd(false))
1643                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1644
1645         return 0;
1646 }
1647
1648 bool check_id(const char *name) {
1649         if(!name || !*name)
1650                 return false;
1651
1652         for(int i = 0; i < strlen(name); i++) {
1653                 if(!isalnum(name[i]) && name[i] != '_')
1654                         return false;
1655         }
1656
1657         return true;
1658 }
1659
1660 static bool try_bind(int port) {
1661         struct addrinfo *ai = NULL;
1662         struct addrinfo hint = {
1663                 .ai_flags = AI_PASSIVE,
1664                 .ai_family = AF_UNSPEC,
1665                 .ai_socktype = SOCK_STREAM,
1666                 .ai_protocol = IPPROTO_TCP,
1667         };
1668
1669         char portstr[16];
1670         snprintf(portstr, sizeof portstr, "%d", port);
1671
1672         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1673                 return false;
1674
1675         while(ai) {
1676                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1677                 if(!fd)
1678                         return false;
1679                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1680                 closesocket(fd);
1681                 if(result)
1682                         return false;
1683                 ai = ai->ai_next;
1684         }
1685
1686         return true;
1687 }
1688
1689 static int cmd_init(int argc, char *argv[]) {
1690         if(!access(tinc_conf, F_OK)) {
1691                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1692                 return 1;
1693         }
1694
1695         if(argc > 2) {
1696                 fprintf(stderr, "Too many arguments!\n");
1697                 return 1;
1698         } else if(argc < 2) {
1699                 if(tty) {
1700                         char buf[1024];
1701                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1702                         fflush(stdout);
1703                         if(!fgets(buf, sizeof buf, stdin)) {
1704                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1705                                 return 1;
1706                         }
1707                         int len = rstrip(buf);
1708                         if(!len) {
1709                                 fprintf(stderr, "No name given!\n");
1710                                 return 1;
1711                         }
1712                         name = strdup(buf);
1713                 } else {
1714                         fprintf(stderr, "No Name given!\n");
1715                         return 1;
1716                 }
1717         } else {
1718                 name = strdup(argv[1]);
1719                 if(!*name) {
1720                         fprintf(stderr, "No Name given!\n");
1721                         return 1;
1722                 }
1723         }
1724
1725         if(!check_id(name)) {
1726                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1727                 return 1;
1728         }
1729
1730         if(mkdir(confdir, 0755) && errno != EEXIST) {
1731                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1732                 return 1;
1733         }
1734
1735         if(mkdir(confbase, 0755) && errno != EEXIST) {
1736                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1737                 return 1;
1738         }
1739
1740         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1741                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1742                 return 1;
1743         }
1744
1745         FILE *f = fopen(tinc_conf, "w");
1746         if(!f) {
1747                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1748                 return 1;
1749         }
1750
1751         fprintf(f, "Name = %s\n", name);
1752         fclose(f);
1753
1754         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1755                 return 1;
1756
1757
1758         if(!try_bind(655)) {
1759                 srand(time(NULL));
1760                 int port = 0;
1761                 for(int i = 0; i < 100; i++) {
1762                         port = 0x1000 + (rand() & 0x7fff);
1763                         if(try_bind(port))
1764                                 break;
1765                         port = 0;
1766                 }
1767                 if(port) {
1768                         char *filename;
1769                         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1770                         FILE *f = fopen(filename, "a");
1771                         free(filename);
1772                         if(!f) {
1773                                 port = 0;
1774                         } else {
1775                                 fprintf(f, "Port = %d\n", port);
1776                                 fclose(f);
1777                         }
1778                 }
1779
1780                 if(!port)
1781                         fprintf(stderr, "Warning: could not bind to port 655. Please change tinc's Port manually.\n");
1782                 else
1783                         fprintf(stderr, "Warning: could not bind to port 655. Tinc will instead listen on port %d.\n", port);
1784         }
1785
1786 #ifndef HAVE_MINGW
1787         char *filename;
1788         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1789         if(access(filename, F_OK)) {
1790                 FILE *f = fopen(filename, "w");
1791                 if(!f) {
1792                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1793                         return 1;
1794                 }
1795                 mode_t mask = umask(0);
1796                 umask(mask);
1797                 fchmod(fileno(f), 0755 & ~mask);
1798                 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");
1799                 fclose(f);
1800         }
1801 #endif
1802
1803         return 0;
1804
1805 }
1806
1807 static int cmd_generate_keys(int argc, char *argv[]) {
1808         if(argc > 2) {
1809                 fprintf(stderr, "Too many arguments!\n");
1810                 return 1;
1811         }
1812
1813         if(!name)
1814                 name = get_my_name(false);
1815
1816         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1817 }
1818
1819 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1820         if(argc > 2) {
1821                 fprintf(stderr, "Too many arguments!\n");
1822                 return 1;
1823         }
1824
1825         if(!name)
1826                 name = get_my_name(false);
1827
1828         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1829 }
1830
1831 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1832         if(argc > 1) {
1833                 fprintf(stderr, "Too many arguments!\n");
1834                 return 1;
1835         }
1836
1837         if(!name)
1838                 name = get_my_name(false);
1839
1840         return !ecdsa_keygen(true);
1841 }
1842
1843 static int cmd_help(int argc, char *argv[]) {
1844         usage(false);
1845         return 0;
1846 }
1847
1848 static int cmd_version(int argc, char *argv[]) {
1849         if(argc > 1) {
1850                 fprintf(stderr, "Too many arguments!\n");
1851                 return 1;
1852         }
1853
1854         version();
1855         return 0;
1856 }
1857
1858 static int cmd_info(int argc, char *argv[]) {
1859         if(argc != 2) {
1860                 fprintf(stderr, "Invalid number of arguments.\n");
1861                 return 1;
1862         }
1863
1864         if(!connect_tincd(true))
1865                 return 1;
1866
1867         return info(fd, argv[1]);
1868 }
1869
1870 static const char *conffiles[] = {
1871         "tinc.conf",
1872         "tinc-up",
1873         "tinc-down",
1874         "subnet-up",
1875         "subnet-down",
1876         "host-up",
1877         "host-down",
1878         NULL,
1879 };
1880
1881 static int cmd_edit(int argc, char *argv[]) {
1882         if(argc != 2) {
1883                 fprintf(stderr, "Invalid number of arguments.\n");
1884                 return 1;
1885         }
1886
1887         char *filename = NULL;
1888
1889         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1890                 for(int i = 0; conffiles[i]; i++) {
1891                         if(!strcmp(argv[1], conffiles[i])) {
1892                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1893                                 break;
1894                         }
1895                 }
1896         } else {
1897                 argv[1] += 6;
1898         }
1899
1900         if(!filename) {
1901                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1902                 char *dash = strchr(argv[1], '-');
1903                 if(dash) {
1904                         *dash++ = 0;
1905                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1906                                 fprintf(stderr, "Invalid configuration filename.\n");
1907                                 return 1;
1908                         }
1909                 }
1910         }
1911
1912         char *command;
1913 #ifndef HAVE_MINGW
1914         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1915 #else
1916         xasprintf(&command, "edit \"%s\"", filename);
1917 #endif
1918         int result = system(command);
1919         if(result)
1920                 return result;
1921
1922         // Silently try notifying a running tincd of changes.
1923         if(connect_tincd(false))
1924                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1925
1926         return 0;
1927 }
1928
1929 static int export(const char *name, FILE *out) {
1930         char *filename;
1931         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1932         FILE *in = fopen(filename, "r");
1933         if(!in) {
1934                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1935                 return 1;
1936         }
1937
1938         fprintf(out, "Name = %s\n", name);
1939         char buf[4096];
1940         while(fgets(buf, sizeof buf, in)) {
1941                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1942                         fputs(buf, out);
1943         }
1944
1945         if(ferror(in)) {
1946                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1947                 fclose(in);
1948                 return 1;
1949         }
1950
1951         fclose(in);
1952         return 0;
1953 }
1954
1955 static int cmd_export(int argc, char *argv[]) {
1956         if(argc > 1) {
1957                 fprintf(stderr, "Too many arguments!\n");
1958                 return 1;
1959         }
1960
1961         char *name = get_my_name(true);
1962         if(!name)
1963                 return 1;
1964
1965         int result = export(name, stdout);
1966         if(!tty)
1967                 fclose(stdout);
1968
1969         free(name);
1970         return result;
1971 }
1972
1973 static int cmd_export_all(int argc, char *argv[]) {
1974         if(argc > 1) {
1975                 fprintf(stderr, "Too many arguments!\n");
1976                 return 1;
1977         }
1978
1979         DIR *dir = opendir(hosts_dir);
1980         if(!dir) {
1981                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1982                 return 1;
1983         }
1984
1985         bool first = true;
1986         int result = 0;
1987         struct dirent *ent;
1988
1989         while((ent = readdir(dir))) {
1990                 if(!check_id(ent->d_name))
1991                         continue;
1992
1993                 if(first)
1994                         first = false;
1995                 else
1996                         printf("#---------------------------------------------------------------#\n");
1997
1998                 result |= export(ent->d_name, stdout);
1999         }
2000
2001         closedir(dir);
2002         if(!tty)
2003                 fclose(stdout);
2004         return result;
2005 }
2006
2007 static int cmd_import(int argc, char *argv[]) {
2008         if(argc > 1) {
2009                 fprintf(stderr, "Too many arguments!\n");
2010                 return 1;
2011         }
2012
2013         FILE *in = stdin;
2014         FILE *out = NULL;
2015
2016         char buf[4096];
2017         char name[4096];
2018         char *filename = NULL;
2019         int count = 0;
2020         bool firstline = true;
2021
2022         while(fgets(buf, sizeof buf, in)) {
2023                 if(sscanf(buf, "Name = %s", name) == 1) {
2024                         firstline = false;
2025
2026                         if(!check_id(name)) {
2027                                 fprintf(stderr, "Invalid Name in input!\n");
2028                                 return 1;
2029                         }
2030
2031                         if(out)
2032                                 fclose(out);
2033
2034                         free(filename);
2035                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2036
2037                         if(!force && !access(filename, F_OK)) {
2038                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2039                                 out = NULL;
2040                                 continue;
2041                         }
2042
2043                         out = fopen(filename, "w");
2044                         if(!out) {
2045                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2046                                 return 1;
2047                         }
2048
2049                         count++;
2050                         continue;
2051                 } else if(firstline) {
2052                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2053                         firstline = false;
2054                 }
2055
2056
2057                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2058                         continue;
2059
2060                 if(out) {
2061                         if(fputs(buf, out) < 0) {
2062                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2063                                 return 1;
2064                         }
2065                 }
2066         }
2067
2068         if(out)
2069                 fclose(out);
2070
2071         if(count) {
2072                 fprintf(stderr, "Imported %d host configuration files.\n", count);
2073                 return 0;
2074         } else {
2075                 fprintf(stderr, "No host configuration files imported.\n");
2076                 return 1;
2077         }
2078 }
2079
2080 static int cmd_exchange(int argc, char *argv[]) {
2081         return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2082 }
2083
2084 static int cmd_exchange_all(int argc, char *argv[]) {
2085         return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2086 }
2087
2088 static const struct {
2089         const char *command;
2090         int (*function)(int argc, char *argv[]);
2091         bool hidden;
2092 } commands[] = {
2093         {"start", cmd_start},
2094         {"stop", cmd_stop},
2095         {"restart", cmd_restart},
2096         {"reload", cmd_reload},
2097         {"dump", cmd_dump},
2098         {"purge", cmd_purge},
2099         {"debug", cmd_debug},
2100         {"retry", cmd_retry},
2101         {"connect", cmd_connect},
2102         {"disconnect", cmd_disconnect},
2103         {"top", cmd_top},
2104         {"pcap", cmd_pcap},
2105         {"log", cmd_log},
2106         {"pid", cmd_pid},
2107         {"config", cmd_config, true},
2108         {"add", cmd_config},
2109         {"del", cmd_config},
2110         {"get", cmd_config},
2111         {"set", cmd_config},
2112         {"init", cmd_init},
2113         {"generate-keys", cmd_generate_keys},
2114         {"generate-rsa-keys", cmd_generate_rsa_keys},
2115         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2116         {"help", cmd_help},
2117         {"version", cmd_version},
2118         {"info", cmd_info},
2119         {"edit", cmd_edit},
2120         {"export", cmd_export},
2121         {"export-all", cmd_export_all},
2122         {"import", cmd_import},
2123         {"exchange", cmd_exchange},
2124         {"exchange-all", cmd_exchange_all},
2125         {"invite", cmd_invite},
2126         {"join", cmd_join},
2127         {NULL, NULL},
2128 };
2129
2130 #ifdef HAVE_READLINE
2131 static char *complete_command(const char *text, int state) {
2132         static int i;
2133
2134         if(!state)
2135                 i = 0;
2136         else
2137                 i++;
2138
2139         while(commands[i].command) {
2140                 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2141                         return xstrdup(commands[i].command);
2142                 i++;
2143         }
2144
2145         return NULL;
2146 }
2147
2148 static char *complete_dump(const char *text, int state) {
2149         const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2150         static int i;
2151
2152         if(!state)
2153                 i = 0;
2154         else
2155                 i++;
2156
2157         while(matches[i]) {
2158                 if(!strncasecmp(matches[i], text, strlen(text)))
2159                         return xstrdup(matches[i]);
2160                 i++;
2161         }
2162
2163         return NULL;
2164 }
2165
2166 static char *complete_config(const char *text, int state) {
2167         static int i;
2168
2169         if(!state)
2170                 i = 0;
2171         else
2172                 i++;
2173
2174         while(variables[i].name) {
2175                 char *dot = strchr(text, '.');
2176                 if(dot) {
2177                         if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2178                                 char *match;
2179                                 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2180                                 return match;
2181                         }
2182                 } else {
2183                         if(!strncasecmp(variables[i].name, text, strlen(text)))
2184                                 return xstrdup(variables[i].name);
2185                 }
2186                 i++;
2187         }
2188
2189         return NULL;
2190 }
2191
2192 static char *complete_info(const char *text, int state) {
2193         static int i;
2194         if(!state) {
2195                 i = 0;
2196                 if(!connect_tincd(false))
2197                         return NULL;
2198                 // Check the list of nodes
2199                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2200                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2201         }
2202
2203         while(recvline(fd, line, sizeof line)) {
2204                 char item[4096];
2205                 int n = sscanf(line, "%d %d %s", &code, &req, item);
2206                 if(n == 2) {
2207                         i++;
2208                         if(i >= 2)
2209                                 break;
2210                         else
2211                                 continue;
2212                 }
2213
2214                 if(n != 3) {
2215                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2216                         break;
2217                 }
2218
2219                 if(!strncmp(item, text, strlen(text)))
2220                         return xstrdup(strip_weight(item));
2221         }
2222
2223         return NULL;
2224 }
2225
2226 static char *complete_nothing(const char *text, int state) {
2227         return NULL;
2228 }
2229
2230 static char **completion (const char *text, int start, int end) {
2231         char **matches = NULL;
2232
2233         if(!start)
2234                 matches = rl_completion_matches(text, complete_command);
2235         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2236                 matches = rl_completion_matches(text, complete_dump);
2237         else if(!strncasecmp(rl_line_buffer, "add ", 4))
2238                 matches = rl_completion_matches(text, complete_config);
2239         else if(!strncasecmp(rl_line_buffer, "del ", 4))
2240                 matches = rl_completion_matches(text, complete_config);
2241         else if(!strncasecmp(rl_line_buffer, "get ", 4))
2242                 matches = rl_completion_matches(text, complete_config);
2243         else if(!strncasecmp(rl_line_buffer, "set ", 4))
2244                 matches = rl_completion_matches(text, complete_config);
2245         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2246                 matches = rl_completion_matches(text, complete_info);
2247
2248         return matches;
2249 }
2250 #endif
2251
2252 static int cmd_shell(int argc, char *argv[]) {
2253         char *prompt;
2254         xasprintf(&prompt, "%s> ", identname);
2255         int result = 0;
2256         char buf[4096];
2257         char *line = NULL;
2258         int maxargs = argc + 16;
2259         char **nargv = xmalloc(maxargs * sizeof *nargv);
2260
2261         for(int i = 0; i < argc; i++)
2262                 nargv[i] = argv[i];
2263
2264 #ifdef HAVE_READLINE
2265         rl_readline_name = "tinc";
2266         rl_completion_entry_function = complete_nothing;
2267         rl_attempted_completion_function = completion;
2268         rl_filename_completion_desired = 0;
2269         char *copy = NULL;
2270 #endif
2271
2272         while(true) {
2273 #ifdef HAVE_READLINE
2274                 if(tty) {
2275                         free(copy);
2276                         free(line);
2277                         rl_basic_word_break_characters = "\t\n ";
2278                         line = readline(prompt);
2279                         if(line)
2280                                 copy = xstrdup(line);
2281                 } else {
2282                         line = fgets(buf, sizeof buf, stdin);
2283                 }
2284 #else
2285                 if(tty)
2286                         fputs(prompt, stdout);
2287
2288                 line = fgets(buf, sizeof buf, stdin);
2289 #endif
2290
2291                 if(!line)
2292                         break;
2293
2294                 /* Ignore comments */
2295
2296                 if(*line == '#')
2297                         continue;
2298
2299                 /* Split */
2300
2301                 int nargc = argc;
2302                 char *p = line + strspn(line, " \t\n");
2303                 char *next = strtok(p, " \t\n");
2304
2305                 while(p && *p) {
2306                         if(nargc >= maxargs) {
2307                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2308                                 abort();
2309                                 maxargs *= 2;
2310                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2311                         }
2312
2313                         nargv[nargc++] = p;
2314                         p = next;
2315                         next = strtok(NULL, " \t\n");
2316                 }
2317
2318                 if(nargc == argc)
2319                         continue;
2320
2321                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2322                         return result;
2323
2324                 bool found = false;
2325
2326                 for(int i = 0; commands[i].command; i++) {
2327                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2328                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2329                                 found = true;
2330                                 break;
2331                         }
2332                 }
2333
2334 #ifdef HAVE_READLINE
2335                 if(tty && found)
2336                         add_history(copy);
2337 #endif
2338
2339                 if(!found) {
2340                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2341                         result |= 1;
2342                 }
2343         }
2344
2345         free(nargv);
2346
2347         if(tty)
2348                 printf("\n");
2349         return result;
2350 }
2351
2352
2353 int main(int argc, char *argv[]) {
2354         program_name = argv[0];
2355         orig_argv = argv;
2356         orig_argc = argc;
2357
2358         if(!parse_options(argc, argv))
2359                 return 1;
2360
2361         make_names();
2362         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2363         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2364
2365         if(show_version) {
2366                 version();
2367                 return 0;
2368         }
2369
2370         if(show_help) {
2371                 usage(false);
2372                 return 0;
2373         }
2374
2375         crypto_init();
2376
2377         tty = isatty(0) && isatty(1);
2378
2379         if(optind >= argc)
2380                 return cmd_shell(argc, argv);
2381
2382         for(int i = 0; commands[i].command; i++) {
2383                 if(!strcasecmp(argv[optind], commands[i].command))
2384                         return commands[i].function(argc - optind, argv + optind);
2385         }
2386
2387         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2388         usage(true);
2389         return 1;
2390 }