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