Allow the log output to be stopped with control-C in tinc's shell.
[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 mkdir(a, b) mkdir(a)
44 #define SCRIPTEXTENSION ".bat"
45 #else
46 #define SCRIPTEXTENSION ""
47 #endif
48
49 static char **orig_argv;
50 static int orig_argc;
51
52 /* If nonzero, display usage information and exit. */
53 static bool show_help = false;
54
55 /* If nonzero, print the version on standard output and exit.  */
56 static bool show_version = false;
57
58 static char *name = NULL;
59 static char controlcookie[1025];
60 char *tinc_conf = NULL;
61 char *hosts_dir = NULL;
62 struct timeval now;
63
64 // Horrible global variables...
65 static int pid = 0;
66 int fd = -1;
67 char line[4096];
68 static int code;
69 static int req;
70 static int result;
71 static bool force = false;
72 bool tty = true;
73 bool confbasegiven = false;
74 bool netnamegiven = false;
75
76 #ifdef HAVE_MINGW
77 static struct WSAData wsa_state;
78 #endif
79
80 static struct option const long_options[] = {
81         {"config", required_argument, NULL, 'c'},
82         {"net", required_argument, NULL, 'n'},
83         {"help", no_argument, NULL, 1},
84         {"version", no_argument, NULL, 2},
85         {"pidfile", required_argument, NULL, 3},
86         {"force", no_argument, NULL, 4},
87         {NULL, 0, NULL, 0}
88 };
89
90 static void version(void) {
91         printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
92                    VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
93         printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
94                         "See the AUTHORS file for a complete list.\n\n"
95                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
96                         "and you are welcome to redistribute it under certain conditions;\n"
97                         "see the file COPYING for details.\n");
98 }
99
100 static void usage(bool status) {
101         if(status) {
102                 fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
103         } else {
104                 printf("Usage: %s [options] command\n\n", program_name);
105                 printf("Valid options are:\n"
106                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
107                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
108                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
109                                 "      --help              Display this help and exit.\n"
110                                 "      --version           Output version information and exit.\n"
111                                 "\n"
112                                 "Valid commands are:\n"
113                                 "  init [name]                Create initial configuration files.\n"
114                                 "  get VARIABLE               Print current value of VARIABLE\n"
115                                 "  set VARIABLE VALUE         Set VARIABLE to VALUE\n"
116                                 "  add VARIABLE VALUE         Add VARIABLE with the given VALUE\n"
117                                 "  del VARIABLE [VALUE]       Remove VARIABLE [only ones with watching VALUE]\n"
118                                 "  start [tincd options]      Start tincd.\n"
119                                 "  stop                       Stop tincd.\n"
120                                 "  restart                    Restart tincd.\n"
121                                 "  reload                     Partially reload configuration of running tincd.\n"
122                                 "  pid                        Show PID of currently running tincd.\n"
123                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
124                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
125                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
126                                 "  dump                       Dump a list of one of the following things:\n"
127                                 "    [reachable] nodes        - all known nodes in the VPN\n"
128                                 "    edges                    - all known connections in the VPN\n"
129                                 "    subnets                  - all known subnets in the VPN\n"
130                                 "    connections              - all meta connections with ourself\n"
131                                 "    [di]graph                - graph of the VPN in dotty format\n"
132                                 "  info NODE|SUBNET|ADDRESS   Give information about a particular NODE, SUBNET or ADDRESS.\n"
133                                 "  purge                      Purge unreachable nodes\n"
134                                 "  debug N                    Set debug level\n"
135                                 "  retry                      Retry all outgoing connections\n"
136                                 "  disconnect NODE            Close meta connection with NODE\n"
137 #ifdef HAVE_CURSES
138                                 "  top                        Show real-time statistics\n"
139 #endif
140                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
141                                 "  log [level]                Dump log output [up to the specified level]\n"
142                                 "  export                     Export host configuration of local node to standard output\n"
143                                 "  export-all                 Export all host configuration files to standard output\n"
144                                 "  import [--force]           Import host configuration file(s) from standard input\n"
145                                 "  exchange [--force]         Same as export followed by import\n"
146                                 "  exchange-all [--force]     Same as export-all followed by import\n"
147                                 "  invite NODE [...]          Generate an invitation for NODE\n"
148                                 "  join INVITATION            Join a VPN using an INVITIATION\n"
149                                 "\n");
150                 printf("Report bugs to tinc@tinc-vpn.org.\n");
151         }
152 }
153
154 static bool parse_options(int argc, char **argv) {
155         int r;
156         int option_index = 0;
157
158         while((r = getopt_long(argc, argv, "+c:n:", long_options, &option_index)) != EOF) {
159                 switch (r) {
160                         case 0:   /* long option */
161                                 break;
162
163                         case 'c': /* config file */
164                                 confbase = xstrdup(optarg);
165                                 confbasegiven = true;
166                                 break;
167
168                         case 'n': /* net name given */
169                                 netname = xstrdup(optarg);
170                                 break;
171
172                         case 1:   /* show help */
173                                 show_help = true;
174                                 break;
175
176                         case 2:   /* show version */
177                                 show_version = true;
178                                 break;
179
180                         case 3:   /* open control socket here */
181                                 pidfilename = xstrdup(optarg);
182                                 break;
183
184                         case 4:   /* force */
185                                 force = true;
186                                 break;
187
188                         case '?': /* wrong options */
189                                 usage(true);
190                                 return false;
191
192                         default:
193                                 break;
194                 }
195         }
196
197         if(!netname && (netname = getenv("NETNAME")))
198                 netname = xstrdup(netname);
199
200         /* netname "." is special: a "top-level name" */
201
202         if(netname && (!*netname || !strcmp(netname, "."))) {
203                 free(netname);
204                 netname = NULL;
205         }
206
207         if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
208                 fprintf(stderr, "Invalid character in netname!\n");
209                 return false;
210         }
211
212         return true;
213 }
214
215 static void disable_old_keys(const char *filename, const char *what) {
216         char tmpfile[PATH_MAX] = "";
217         char buf[1024];
218         bool disabled = false;
219         bool block = false;
220         bool error = false;
221         FILE *r, *w;
222
223         r = fopen(filename, "r");
224         if(!r)
225                 return;
226
227         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
228
229         w = fopen(tmpfile, "w");
230
231         while(fgets(buf, sizeof buf, r)) {
232                 if(!block && !strncmp(buf, "-----BEGIN ", 11)) {
233                         if((strstr(buf, " EC ") && strstr(what, "ECDSA")) || (strstr(buf, " RSA ") && strstr(what, "RSA"))) {
234                                 disabled = true;
235                                 block = true;
236                         }
237                 }
238
239                 bool ecdsapubkey = !strncasecmp(buf, "ECDSAPublicKey", 14) && strchr(" \t=", buf[14]) && strstr(what, "ECDSA");
240
241                 if(ecdsapubkey)
242                         disabled = true;
243
244                 if(w) {
245                         if(block || ecdsapubkey)
246                                 fputc('#', w);
247                         if(fputs(buf, w) < 0) {
248                                 error = true;
249                                 break;
250                         }
251                 }
252
253                 if(block && !strncmp(buf, "-----END ", 9))
254                         block = false;
255         }
256
257         if(w)
258                 if(fclose(w) < 0)
259                         error = true;
260         if(ferror(r) || fclose(r) < 0)
261                 error = true;
262
263         if(disabled) {
264                 if(!w || error) {
265                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
266                         if(w)
267                                 unlink(tmpfile);
268                         return;
269                 }
270
271 #ifdef HAVE_MINGW
272                 // We cannot atomically replace files on Windows.
273                 char bakfile[PATH_MAX] = "";
274                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
275                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
276                         rename(bakfile, filename);
277 #else
278                 if(rename(tmpfile, filename)) {
279 #endif
280                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
281                 } else  {
282 #ifdef HAVE_MINGW
283                         unlink(bakfile);
284 #endif
285                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
286                 }
287         }
288
289         unlink(tmpfile);
290 }
291
292 static FILE *ask_and_open(const char *filename, const char *what, const char *mode, bool ask) {
293         FILE *r;
294         char *directory;
295         char buf[PATH_MAX];
296         char buf2[PATH_MAX];
297
298         /* Check stdin and stdout */
299         if(ask && tty) {
300                 /* Ask for a file and/or directory name. */
301                 fprintf(stdout, "Please enter a file to save %s to [%s]: ", what, filename);
302                 fflush(stdout);
303
304                 if(fgets(buf, sizeof buf, stdin) == NULL) {
305                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
306                         return NULL;
307                 }
308
309                 size_t len = strlen(buf);
310                 if(len)
311                         buf[--len] = 0;
312
313                 if(len)
314                         filename = buf;
315         }
316
317 #ifdef HAVE_MINGW
318         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
319 #else
320         if(filename[0] != '/') {
321 #endif
322                 /* The directory is a relative path or a filename. */
323                 directory = get_current_dir_name();
324                 snprintf(buf2, sizeof buf2, "%s" SLASH "%s", directory, filename);
325                 filename = buf2;
326         }
327
328         umask(0077); /* Disallow everything for group and other */
329
330         disable_old_keys(filename, what);
331
332         /* Open it first to keep the inode busy */
333
334         r = fopen(filename, mode);
335
336         if(!r) {
337                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
338                 return NULL;
339         }
340
341         return r;
342 }
343
344 /*
345   Generate a public/private ECDSA keypair, and ask for a file to store
346   them in.
347 */
348 static bool ecdsa_keygen(bool ask) {
349         ecdsa_t *key;
350         FILE *f;
351         char *pubname, *privname;
352
353         fprintf(stderr, "Generating ECDSA keypair:\n");
354
355         if(!(key = ecdsa_generate())) {
356                 fprintf(stderr, "Error during key generation!\n");
357                 return false;
358         } else
359                 fprintf(stderr, "Done.\n");
360
361         xasprintf(&privname, "%s" SLASH "ecdsa_key.priv", confbase);
362         f = ask_and_open(privname, "private ECDSA key", "a", ask);
363         free(privname);
364
365         if(!f)
366                 return false;
367
368 #ifdef HAVE_FCHMOD
369         /* Make it unreadable for others. */
370         fchmod(fileno(f), 0600);
371 #endif
372
373         if(!ecdsa_write_pem_private_key(key, f)) {
374                 fprintf(stderr, "Error writing private key!\n");
375                 ecdsa_free(key);
376                 fclose(f);
377                 return false;
378         }
379
380         fclose(f);
381
382         if(name)
383                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
384         else
385                 xasprintf(&pubname, "%s" SLASH "ecdsa_key.pub", confbase);
386
387         f = ask_and_open(pubname, "public ECDSA key", "a", ask);
388         free(pubname);
389
390         if(!f)
391                 return false;
392
393         char *pubkey = ecdsa_get_base64_public_key(key);
394         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
395         free(pubkey);
396
397         fclose(f);
398         ecdsa_free(key);
399
400         return true;
401 }
402
403 /*
404   Generate a public/private RSA keypair, and ask for a file to store
405   them in.
406 */
407 static bool rsa_keygen(int bits, bool ask) {
408         rsa_t *key;
409         FILE *f;
410         char *pubname, *privname;
411
412         fprintf(stderr, "Generating %d bits keys:\n", bits);
413
414         if(!(key = rsa_generate(bits, 0x10001))) {
415                 fprintf(stderr, "Error during key generation!\n");
416                 return false;
417         } else
418                 fprintf(stderr, "Done.\n");
419
420         xasprintf(&privname, "%s" SLASH "rsa_key.priv", confbase);
421         f = ask_and_open(privname, "private RSA key", "a", ask);
422         free(privname);
423
424         if(!f)
425                 return false;
426
427 #ifdef HAVE_FCHMOD
428         /* Make it unreadable for others. */
429         fchmod(fileno(f), 0600);
430 #endif
431
432         if(!rsa_write_pem_private_key(key, f)) {
433                 fprintf(stderr, "Error writing private key!\n");
434                 fclose(f);
435                 rsa_free(key);
436                 return false;
437         }
438
439         fclose(f);
440
441         if(name)
442                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
443         else
444                 xasprintf(&pubname, "%s" SLASH "rsa_key.pub", confbase);
445
446         f = ask_and_open(pubname, "public RSA key", "a", ask);
447         free(pubname);
448
449         if(!f)
450                 return false;
451
452         if(!rsa_write_pem_public_key(key, f)) {
453                 fprintf(stderr, "Error writing public key!\n");
454                 fclose(f);
455                 rsa_free(key);
456                 return false;
457         }
458
459         fclose(f);
460         rsa_free(key);
461
462         return true;
463 }
464
465 char buffer[4096];
466 size_t blen = 0;
467
468 bool recvline(int fd, char *line, size_t len) {
469         char *newline = NULL;
470
471         if(!fd)
472                 abort();
473
474         while(!(newline = memchr(buffer, '\n', blen))) {
475                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
476                 if(result == -1 && errno == EINTR)
477                         continue;
478                 else if(result <= 0)
479                         return false;
480                 blen += result;
481         }
482
483         if(newline - buffer >= len)
484                 return false;
485
486         len = newline - buffer;
487
488         memcpy(line, buffer, len);
489         line[len] = 0;
490         memmove(buffer, newline + 1, blen - len - 1);
491         blen -= len + 1;
492
493         return true;
494 }
495
496 bool recvdata(int fd, char *data, size_t len) {
497         if(len == -1)
498                 len = blen;
499
500         while(blen < len) {
501                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
502                 if(result == -1 && errno == EINTR)
503                         continue;
504                 else if(result <= 0)
505                         return false;
506                 blen += result;
507         }
508
509         memcpy(data, buffer, len);
510         memmove(buffer, buffer + len, blen - len);
511         blen -= len;
512
513         return true;
514 }
515
516 bool sendline(int fd, char *format, ...) {
517         static char buffer[4096];
518         char *p = buffer;
519         int blen = 0;
520         va_list ap;
521
522         va_start(ap, format);
523         blen = vsnprintf(buffer, sizeof buffer, format, ap);
524         va_end(ap);
525
526         if(blen < 1 || blen >= sizeof buffer)
527                 return false;
528
529         buffer[blen] = '\n';
530         blen++;
531
532         while(blen) {
533                 int result = send(fd, p, blen, 0);
534                 if(result == -1 && errno == EINTR)
535                         continue;
536                 else if(result <= 0)
537                         return false;
538                 p += result;
539                 blen -= result;
540         }
541
542         return true;
543 }
544
545 static void pcap(int fd, FILE *out, int snaplen) {
546         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
547         char data[9018];
548
549         struct {
550                 uint32_t magic;
551                 uint16_t major;
552                 uint16_t minor;
553                 uint32_t tz_offset;
554                 uint32_t tz_accuracy;
555                 uint32_t snaplen;
556                 uint32_t ll_type;
557         } header = {
558                 0xa1b2c3d4,
559                 2, 4,
560                 0, 0,
561                 snaplen ?: sizeof data,
562                 1,
563         };
564
565         struct {
566                 uint32_t tv_sec;
567                 uint32_t tv_usec;
568                 uint32_t len;
569                 uint32_t origlen;
570         } packet;
571
572         struct timeval tv;
573
574         fwrite(&header, sizeof header, 1, out);
575         fflush(out);
576
577         char line[32];
578         while(recvline(fd, line, sizeof line)) {
579                 int code, req, len;
580                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
581                 gettimeofday(&tv, NULL);
582                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
583                         break;
584                 if(!recvdata(fd, data, len))
585                         break;
586                 packet.tv_sec = tv.tv_sec;
587                 packet.tv_usec = tv.tv_usec;
588                 packet.len = len;
589                 packet.origlen = len;
590                 fwrite(&packet, sizeof packet, 1, out);
591                 fwrite(data, len, 1, out);
592                 fflush(out);
593         }
594 }
595
596 static void logcontrol(int fd, FILE *out, int level) {
597         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
598         char data[1024];
599         char line[32];
600
601         while(recvline(fd, line, sizeof line)) {
602                 int code, req, len;
603                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
604                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
605                         break;
606                 if(!recvdata(fd, data, len))
607                         break;
608                 fwrite(data, len, 1, out);
609                 fputc('\n', out);
610                 fflush(out);
611         }
612 }
613
614 #ifdef HAVE_MINGW
615 static bool remove_service(void) {
616         SC_HANDLE manager = NULL;
617         SC_HANDLE service = NULL;
618         SERVICE_STATUS status = {0};
619
620         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
621         if(!manager) {
622                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
623                 return false;
624         }
625
626         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
627
628         if(!service) {
629                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
630                 return false;
631         }
632
633         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
634                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
635         else
636                 fprintf(stderr, "%s service stopped\n", identname);
637
638         if(!DeleteService(service)) {
639                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
640                 return false;
641         }
642
643         fprintf(stderr, "%s service removed\n", identname);
644
645         return true;
646 }
647 #endif
648
649 bool connect_tincd(bool verbose) {
650         if(fd >= 0) {
651                 fd_set r;
652                 FD_ZERO(&r);
653                 FD_SET(fd, &r);
654                 struct timeval tv = {0, 0};
655                 if(select(fd + 1, &r, NULL, NULL, &tv)) {
656                         fprintf(stderr, "Previous connection to tincd lost, reconnecting.\n");
657                         close(fd);
658                         fd = -1;
659                 } else {
660                         return true;
661                 }
662         }
663
664         FILE *f = fopen(pidfilename, "r");
665         if(!f) {
666                 if(verbose)
667                         fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
668                 return false;
669         }
670
671         char host[129];
672         char port[129];
673
674         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
675                 if(verbose)
676                         fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
677                 fclose(f);
678                 return false;
679         }
680
681         fclose(f);
682
683 #ifdef HAVE_MINGW
684         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
685                 if(verbose)
686                         fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
687                 return false;
688         }
689 #endif
690
691 #ifndef HAVE_MINGW
692         struct sockaddr_un sa;
693         sa.sun_family = AF_UNIX;
694         strncpy(sa.sun_path, unixsocketname, sizeof sa.sun_path);
695
696         fd = socket(AF_UNIX, SOCK_STREAM, 0);
697         if(fd < 0) {
698                 if(verbose)
699                         fprintf(stderr, "Cannot create UNIX socket: %s\n", sockstrerror(sockerrno));
700                 return false;
701         }
702
703         if(connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) {
704                 if(verbose)
705                         fprintf(stderr, "Cannot connect to UNIX socket %s: %s\n", unixsocketname, sockstrerror(sockerrno));
706                 close(fd);
707                 fd = -1;
708                 return false;
709         }
710 #else
711         struct addrinfo hints = {
712                 .ai_family = AF_UNSPEC,
713                 .ai_socktype = SOCK_STREAM,
714                 .ai_protocol = IPPROTO_TCP,
715                 .ai_flags = 0,
716         };
717
718         struct addrinfo *res = NULL;
719
720         if(getaddrinfo(host, port, &hints, &res) || !res) {
721                 if(verbose)
722                         fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
723                 return false;
724         }
725
726         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
727         if(fd < 0) {
728                 if(verbose)
729                         fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
730                 return false;
731         }
732
733 #ifdef HAVE_MINGW
734         unsigned long arg = 0;
735
736         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
737                 if(verbose)
738                         fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
739         }
740 #endif
741
742         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
743                 if(verbose)
744                         fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
745                 close(fd);
746                 fd = -1;
747                 return false;
748         }
749
750         freeaddrinfo(res);
751 #endif
752
753         char data[4096];
754         int version;
755
756         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
757                 if(verbose)
758                         fprintf(stderr, "Cannot read greeting from control socket: %s\n", sockstrerror(sockerrno));
759                 close(fd);
760                 fd = -1;
761                 return false;
762         }
763
764         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
765
766         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
767                 if(verbose)
768                         fprintf(stderr, "Could not fully establish control socket connection\n");
769                 close(fd);
770                 fd = -1;
771                 return false;
772         }
773
774         return true;
775 }
776
777
778 static int cmd_start(int argc, char *argv[]) {
779         if(connect_tincd(false)) {
780                 if(netname)
781                         fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n", netname, pid);
782                 else
783                         fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
784                 return 0;
785         }
786
787         char *c;
788         char *slash = strrchr(program_name, '/');
789
790 #ifdef HAVE_MINGW
791         if ((c = strrchr(program_name, '\\')) > slash)
792                 slash = c;
793 #endif
794
795         if (slash++)
796                 xasprintf(&c, "%.*stincd", (int)(slash - program_name), program_name);
797         else
798                 c = "tincd";
799
800         int nargc = 0;
801         char **nargv = xzalloc((optind + argc) * sizeof *nargv);
802
803         nargv[nargc++] = c;
804         for(int i = 1; i < optind; i++)
805                 nargv[nargc++] = orig_argv[i];
806         for(int i = 1; i < argc; i++)
807                 nargv[nargc++] = argv[i];
808
809 #ifdef HAVE_MINGW
810         execvp(c, nargv);
811         fprintf(stderr, "Error starting %s: %s\n", c, strerror(errno));
812         return 1;
813 #else
814         pid_t pid = fork();
815         if(pid == -1) {
816                 fprintf(stderr, "Could not fork: %s\n", strerror(errno));
817                 free(nargv);
818                 return 1;
819         }
820
821         if(!pid)
822                 exit(execvp(c, nargv));
823
824         free(nargv);
825
826         int status = -1;
827         if(waitpid(pid, &status, 0) != pid || !WIFEXITED(status) || WEXITSTATUS(status)) {
828                 fprintf(stderr, "Error starting %s\n", c);
829                 return 1;
830         }
831
832         return 0;
833 #endif
834 }
835
836 static int cmd_stop(int argc, char *argv[]) {
837         if(argc > 1) {
838                 fprintf(stderr, "Too many arguments!\n");
839                 return 1;
840         }
841
842 #ifndef HAVE_MINGW
843         if(!connect_tincd(true)) {
844                 if(pid) {
845                         if(kill(pid, SIGTERM)) {
846                                 fprintf(stderr, "Could not send TERM signal to process with PID %u: %s\n", pid, strerror(errno));
847                                 return 1;
848                         }
849
850                         fprintf(stderr, "Sent TERM signal to process with PID %u.\n", pid);
851                         waitpid(pid, NULL, 0);
852                         return 0;
853                 }
854
855                 return 1;
856         }
857
858         sendline(fd, "%d %d", CONTROL, REQ_STOP);
859
860         while(recvline(fd, line, sizeof line)) {
861                 // Wait for tincd to close the connection...
862         }
863 #else
864         if(!remove_service())
865                 return 1;
866 #endif
867         close(fd);
868         pid = 0;
869         fd = -1;
870
871         return 0;
872 }
873
874 static int cmd_restart(int argc, char *argv[]) {
875         cmd_stop(argc, argv);
876         return cmd_start(argc, argv);
877 }
878
879 static int cmd_reload(int argc, char *argv[]) {
880         if(argc > 1) {
881                 fprintf(stderr, "Too many arguments!\n");
882                 return 1;
883         }
884
885         if(!connect_tincd(true))
886                 return 1;
887
888         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
889         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
890                 fprintf(stderr, "Could not reload configuration.\n");
891                 return 1;
892         }
893
894         return 0;
895
896 }
897
898 static int cmd_dump(int argc, char *argv[]) {
899         bool only_reachable = false;
900
901         if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
902                 if(strcasecmp(argv[2], "nodes")) {
903                         fprintf(stderr, "`reachable' only supported for nodes.\n");
904                         usage(true);
905                         return 1;
906                 }
907                 only_reachable = true;
908                 argv++;
909                 argc--;
910         }
911
912         if(argc != 2) {
913                 fprintf(stderr, "Invalid number of arguments.\n");
914                 usage(true);
915                 return 1;
916         }
917
918         if(!connect_tincd(true))
919                 return 1;
920
921         int do_graph = 0;
922
923         if(!strcasecmp(argv[1], "nodes"))
924                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
925         else if(!strcasecmp(argv[1], "edges"))
926                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
927         else if(!strcasecmp(argv[1], "subnets"))
928                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
929         else if(!strcasecmp(argv[1], "connections"))
930                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
931         else if(!strcasecmp(argv[1], "graph")) {
932                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
933                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
934                 do_graph = 1;
935         } else if(!strcasecmp(argv[1], "digraph")) {
936                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
937                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
938                 do_graph = 2;
939         } else {
940                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
941                 usage(true);
942                 return 1;
943         }
944
945         if(do_graph == 1)
946                 printf("graph {\n");
947         else if(do_graph == 2)
948                 printf("digraph {\n");
949
950         while(recvline(fd, line, sizeof line)) {
951                 char node1[4096], node2[4096];
952                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
953                 if(n == 2) {
954                         if(do_graph && req == REQ_DUMP_NODES)
955                                 continue;
956                         else {
957                                 if(do_graph)
958                                         printf("}\n");
959                                 return 0;
960                         }
961                 }
962                 if(n < 2)
963                         break;
964
965                 char node[4096];
966                 char from[4096];
967                 char to[4096];
968                 char subnet[4096];
969                 char host[4096];
970                 char port[4096];
971                 char via[4096];
972                 char nexthop[4096];
973                 int cipher, digest, maclength, compression, distance, socket, weight;
974                 short int pmtu, minmtu, maxmtu;
975                 unsigned int options, status_int;
976                 node_status_t status;
977                 long int last_state_change;
978
979                 switch(req) {
980                         case REQ_DUMP_NODES: {
981                                 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);
982                                 if(n != 16) {
983                                         fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
984                                         return 1;
985                                 }
986
987                                 memcpy(&status, &status_int, sizeof status);
988
989                                 if(do_graph) {
990                                         const char *color = "black";
991                                         if(!strcmp(host, "MYSELF"))
992                                                 color = "green";
993                                         else if(!status.reachable)
994                                                 color = "red";
995                                         else if(strcmp(via, node))
996                                                 color = "orange";
997                                         else if(!status.validkey)
998                                                 color = "black";
999                                         else if(minmtu > 0)
1000                                                 color = "green";
1001                                         printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1002                                 } else {
1003                                         if(only_reachable && !status.reachable)
1004                                                 continue;
1005                                         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",
1006                                                         node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1007                                 }
1008                         } break;
1009
1010                         case REQ_DUMP_EDGES: {
1011                                 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1012                                 if(n != 6) {
1013                                         fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1014                                         return 1;
1015                                 }
1016
1017                                 if(do_graph) {
1018                                         float w = 1 + 65536.0 / weight;
1019                                         if(do_graph == 1 && strcmp(node1, node2) > 0)
1020                                                 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1021                                         else if(do_graph == 2)
1022                                                 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1023                                 } else {
1024                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1025                                 }
1026                         } break;
1027
1028                         case REQ_DUMP_SUBNETS: {
1029                                 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1030                                 if(n != 2) {
1031                                         fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1032                                         return 1;
1033                                 }
1034                                 printf("%s owner %s\n", strip_weight(subnet), node);
1035                         } break;
1036
1037                         case REQ_DUMP_CONNECTIONS: {
1038                                 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1039                                 if(n != 6) {
1040                                         fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1041                                         return 1;
1042                                 }
1043                                 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1044                         } break;
1045
1046                         default:
1047                                 fprintf(stderr, "Unable to parse dump from tincd.\n");
1048                                 return 1;
1049                 }
1050         }
1051
1052         fprintf(stderr, "Error receiving dump.\n");
1053         return 1;
1054 }
1055
1056 static int cmd_purge(int argc, char *argv[]) {
1057         if(argc > 1) {
1058                 fprintf(stderr, "Too many arguments!\n");
1059                 return 1;
1060         }
1061
1062         if(!connect_tincd(true))
1063                 return 1;
1064
1065         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1066         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1067                 fprintf(stderr, "Could not purge old information.\n");
1068                 return 1;
1069         }
1070
1071         return 0;
1072 }
1073
1074 static int cmd_debug(int argc, char *argv[]) {
1075         if(argc != 2) {
1076                 fprintf(stderr, "Invalid number of arguments.\n");
1077                 return 1;
1078         }
1079
1080         if(!connect_tincd(true))
1081                 return 1;
1082
1083         int debuglevel = atoi(argv[1]);
1084         int origlevel;
1085
1086         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1087         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1088                 fprintf(stderr, "Could not set debug level.\n");
1089                 return 1;
1090         }
1091
1092         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1093         return 0;
1094 }
1095
1096 static int cmd_retry(int argc, char *argv[]) {
1097         if(argc > 1) {
1098                 fprintf(stderr, "Too many arguments!\n");
1099                 return 1;
1100         }
1101
1102         if(!connect_tincd(true))
1103                 return 1;
1104
1105         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1106         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1107                 fprintf(stderr, "Could not retry outgoing connections.\n");
1108                 return 1;
1109         }
1110
1111         return 0;
1112 }
1113
1114 static int cmd_connect(int argc, char *argv[]) {
1115         if(argc != 2) {
1116                 fprintf(stderr, "Invalid number of arguments.\n");
1117                 return 1;
1118         }
1119
1120         if(!check_id(argv[1])) {
1121                 fprintf(stderr, "Invalid name for node.\n");
1122                 return 1;
1123         }
1124
1125         if(!connect_tincd(true))
1126                 return 1;
1127
1128         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1129         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1130                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1131                 return 1;
1132         }
1133
1134         return 0;
1135 }
1136
1137 static int cmd_disconnect(int argc, char *argv[]) {
1138         if(argc != 2) {
1139                 fprintf(stderr, "Invalid number of arguments.\n");
1140                 return 1;
1141         }
1142
1143         if(!check_id(argv[1])) {
1144                 fprintf(stderr, "Invalid name for node.\n");
1145                 return 1;
1146         }
1147
1148         if(!connect_tincd(true))
1149                 return 1;
1150
1151         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1152         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1153                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1154                 return 1;
1155         }
1156
1157         return 0;
1158 }
1159
1160 static int cmd_top(int argc, char *argv[]) {
1161         if(argc > 1) {
1162                 fprintf(stderr, "Too many arguments!\n");
1163                 return 1;
1164         }
1165
1166 #ifdef HAVE_CURSES
1167         if(!connect_tincd(true))
1168                 return 1;
1169
1170         top(fd);
1171         return 0;
1172 #else
1173         fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1174         return 1;
1175 #endif
1176 }
1177
1178 static int cmd_pcap(int argc, char *argv[]) {
1179         if(argc > 2) {
1180                 fprintf(stderr, "Too many arguments!\n");
1181                 return 1;
1182         }
1183
1184         if(!connect_tincd(true))
1185                 return 1;
1186
1187         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1188         return 0;
1189 }
1190
1191 #ifdef SIGINT
1192 static void sigint_handler(int sig) {
1193         fprintf(stderr, "\n");
1194         shutdown(fd, SHUT_RDWR);
1195 }
1196 #endif
1197
1198 static int cmd_log(int argc, char *argv[]) {
1199         if(argc > 2) {
1200                 fprintf(stderr, "Too many arguments!\n");
1201                 return 1;
1202         }
1203
1204         if(!connect_tincd(true))
1205                 return 1;
1206
1207 #ifdef SIGINT
1208         signal(SIGINT, sigint_handler);
1209 #endif
1210
1211         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1212
1213 #ifdef SIGINT
1214         signal(SIGINT, SIG_DFL);
1215 #endif
1216
1217         close(fd);
1218         fd = -1;
1219         return 0;
1220 }
1221
1222 static int cmd_pid(int argc, char *argv[]) {
1223         if(argc > 1) {
1224                 fprintf(stderr, "Too many arguments!\n");
1225                 return 1;
1226         }
1227
1228         if(!connect_tincd(true) && !pid)
1229                 return 1;
1230
1231         printf("%d\n", pid);
1232         return 0;
1233 }
1234
1235 int rstrip(char *value) {
1236         int len = strlen(value);
1237         while(len && strchr("\t\r\n ", value[len - 1]))
1238                 value[--len] = 0;
1239         return len;
1240 }
1241
1242 char *get_my_name(bool verbose) {
1243         FILE *f = fopen(tinc_conf, "r");
1244         if(!f) {
1245                 if(verbose)
1246                         fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1247                 return NULL;
1248         }
1249
1250         char buf[4096];
1251         char *value;
1252         while(fgets(buf, sizeof buf, f)) {
1253                 int len = strcspn(buf, "\t =");
1254                 value = buf + len;
1255                 value += strspn(value, "\t ");
1256                 if(*value == '=') {
1257                         value++;
1258                         value += strspn(value, "\t ");
1259                 }
1260                 if(!rstrip(value))
1261                         continue;
1262                 buf[len] = 0;
1263                 if(strcasecmp(buf, "Name"))
1264                         continue;
1265                 if(*value) {
1266                         fclose(f);
1267                         return strdup(value);
1268                 }
1269         }
1270
1271         fclose(f);
1272         if(verbose)
1273                 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1274         return NULL;
1275 }
1276
1277 const var_t variables[] = {
1278         /* Server configuration */
1279         {"AddressFamily", VAR_SERVER},
1280         {"AutoConnect", VAR_SERVER | VAR_SAFE},
1281         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1282         {"BindToInterface", VAR_SERVER},
1283         {"Broadcast", VAR_SERVER | VAR_SAFE},
1284         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1285         {"DecrementTTL", VAR_SERVER},
1286         {"Device", VAR_SERVER},
1287         {"DeviceType", VAR_SERVER},
1288         {"DirectOnly", VAR_SERVER},
1289         {"ECDSAPrivateKeyFile", VAR_SERVER},
1290         {"ExperimentalProtocol", VAR_SERVER},
1291         {"Forwarding", VAR_SERVER},
1292         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1293         {"Hostnames", VAR_SERVER},
1294         {"IffOneQueue", VAR_SERVER},
1295         {"Interface", VAR_SERVER},
1296         {"KeyExpire", VAR_SERVER},
1297         {"LocalDiscovery", VAR_SERVER},
1298         {"MACExpire", 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 }