Add connection rate limiting.
[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         {"MaxConnectionBurst", VAR_SERVER},
1300         {"MaxOutputBufferSize", VAR_SERVER},
1301         {"MaxTimeout", VAR_SERVER},
1302         {"Mode", VAR_SERVER | VAR_SAFE},
1303         {"Name", VAR_SERVER},
1304         {"PingInterval", VAR_SERVER},
1305         {"PingTimeout", VAR_SERVER},
1306         {"PriorityInheritance", VAR_SERVER},
1307         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1308         {"PrivateKeyFile", VAR_SERVER},
1309         {"ProcessPriority", VAR_SERVER},
1310         {"Proxy", VAR_SERVER},
1311         {"ReplayWindow", VAR_SERVER},
1312         {"ScriptsExtension", VAR_SERVER},
1313         {"ScriptsInterpreter", VAR_SERVER},
1314         {"StrictSubnets", VAR_SERVER},
1315         {"TunnelServer", VAR_SERVER},
1316         {"UDPRcvBuf", VAR_SERVER},
1317         {"UDPSndBuf", VAR_SERVER},
1318         {"VDEGroup", VAR_SERVER},
1319         {"VDEPort", VAR_SERVER},
1320         /* Host configuration */
1321         {"Address", VAR_HOST | VAR_MULTIPLE},
1322         {"Cipher", VAR_SERVER | VAR_HOST},
1323         {"ClampMSS", VAR_SERVER | VAR_HOST},
1324         {"Compression", VAR_SERVER | VAR_HOST},
1325         {"Digest", VAR_SERVER | VAR_HOST},
1326         {"ECDSAPublicKey", VAR_HOST},
1327         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1328         {"IndirectData", VAR_SERVER | VAR_HOST},
1329         {"MACLength", VAR_SERVER | VAR_HOST},
1330         {"PMTU", VAR_SERVER | VAR_HOST},
1331         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1332         {"Port", VAR_HOST},
1333         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1334         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1335         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1336         {"TCPOnly", VAR_SERVER | VAR_HOST},
1337         {"Weight", VAR_HOST | VAR_SAFE},
1338         {NULL, 0}
1339 };
1340
1341 static int cmd_config(int argc, char *argv[]) {
1342         if(argc < 2) {
1343                 fprintf(stderr, "Invalid number of arguments.\n");
1344                 return 1;
1345         }
1346
1347         if(strcasecmp(argv[0], "config"))
1348                 argv--, argc++;
1349
1350         int action = -2;
1351         if(!strcasecmp(argv[1], "get")) {
1352                 argv++, argc--;
1353         } else if(!strcasecmp(argv[1], "add")) {
1354                 argv++, argc--, action = 1;
1355         } else if(!strcasecmp(argv[1], "del")) {
1356                 argv++, argc--, action = -1;
1357         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1358                 argv++, argc--, action = 0;
1359         }
1360
1361         if(argc < 2) {
1362                 fprintf(stderr, "Invalid number of arguments.\n");
1363                 return 1;
1364         }
1365
1366         // Concatenate the rest of the command line
1367         strncpy(line, argv[1], sizeof line - 1);
1368         for(int i = 2; i < argc; i++) {
1369                 strncat(line, " ", sizeof line - 1 - strlen(line));
1370                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1371         }
1372
1373         // Liberal parsing into node name, variable name and value.
1374         char *node = NULL;
1375         char *variable;
1376         char *value;
1377         int len;
1378
1379         len = strcspn(line, "\t =");
1380         value = line + len;
1381         value += strspn(value, "\t ");
1382         if(*value == '=') {
1383                 value++;
1384                 value += strspn(value, "\t ");
1385         }
1386         line[len] = '\0';
1387         variable = strchr(line, '.');
1388         if(variable) {
1389                 node = line;
1390                 *variable++ = 0;
1391         } else {
1392                 variable = line;
1393         }
1394
1395         if(!*variable) {
1396                 fprintf(stderr, "No variable given.\n");
1397                 return 1;
1398         }
1399
1400         if(action >= 0 && !*value) {
1401                 fprintf(stderr, "No value for variable given.\n");
1402                 return 1;
1403         }
1404
1405         if(action < -1 && *value)
1406                 action = 0;
1407
1408         /* Some simple checks. */
1409         bool found = false;
1410
1411         for(int i = 0; variables[i].name; i++) {
1412                 if(strcasecmp(variables[i].name, variable))
1413                         continue;
1414
1415                 found = true;
1416                 variable = (char *)variables[i].name;
1417
1418                 /* Discourage use of obsolete variables. */
1419
1420                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1421                         if(force) {
1422                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1423                         } else {
1424                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1425                                 return 1;
1426                         }
1427                 }
1428
1429                 /* Don't put server variables in host config files */
1430
1431                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1432                         if(force) {
1433                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1434                         } else {
1435                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1436                                 return 1;
1437                         }
1438                 }
1439
1440                 /* Should this go into our own host config file? */
1441
1442                 if(!node && !(variables[i].type & VAR_SERVER)) {
1443                         node = get_my_name(true);
1444                         if(!node)
1445                                 return 1;
1446                 }
1447
1448                 break;
1449         }
1450
1451         if(node && !check_id(node)) {
1452                 fprintf(stderr, "Invalid name for node.\n");
1453                 return 1;
1454         }
1455
1456         if(!found) {
1457                 if(force || action < 0) {
1458                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1459                 } else {
1460                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1461                         return 1;
1462                 }
1463         }
1464
1465         // Open the right configuration file.
1466         char *filename;
1467         if(node)
1468                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1469         else
1470                 filename = tinc_conf;
1471
1472         FILE *f = fopen(filename, "r");
1473         if(!f) {
1474                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1475                 return 1;
1476         }
1477
1478         char *tmpfile = NULL;
1479         FILE *tf = NULL;
1480
1481         if(action >= -1) {
1482                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1483                 tf = fopen(tmpfile, "w");
1484                 if(!tf) {
1485                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1486                         fclose(f);
1487                         return 1;
1488                 }
1489         }
1490
1491         // Copy the file, making modifications on the fly, unless we are just getting a value.
1492         char buf1[4096];
1493         char buf2[4096];
1494         bool set = false;
1495         bool removed = false;
1496         found = false;
1497
1498         while(fgets(buf1, sizeof buf1, f)) {
1499                 buf1[sizeof buf1 - 1] = 0;
1500                 strncpy(buf2, buf1, sizeof buf2);
1501
1502                 // Parse line in a simple way
1503                 char *bvalue;
1504                 int len;
1505
1506                 len = strcspn(buf2, "\t =");
1507                 bvalue = buf2 + len;
1508                 bvalue += strspn(bvalue, "\t ");
1509                 if(*bvalue == '=') {
1510                         bvalue++;
1511                         bvalue += strspn(bvalue, "\t ");
1512                 }
1513                 rstrip(bvalue);
1514                 buf2[len] = '\0';
1515
1516                 // Did it match?
1517                 if(!strcasecmp(buf2, variable)) {
1518                         // Get
1519                         if(action < -1) {
1520                                 found = true;
1521                                 printf("%s\n", bvalue);
1522                         // Del
1523                         } else if(action == -1) {
1524                                 if(!*value || !strcasecmp(bvalue, value)) {
1525                                         removed = true;
1526                                         continue;
1527                                 }
1528                         // Set
1529                         } else if(action == 0) {
1530                                 // Already set? Delete the rest...
1531                                 if(set)
1532                                         continue;
1533                                 // Otherwise, replace.
1534                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1535                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1536                                         return 1;
1537                                 }
1538                                 set = true;
1539                                 continue;
1540                         }
1541                 }
1542
1543                 if(action >= -1) {
1544                         // Copy original line...
1545                         if(fputs(buf1, tf) < 0) {
1546                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1547                                 return 1;
1548                         }
1549
1550                         // Add newline if it is missing...
1551                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1552                                 if(fputc('\n', tf) < 0) {
1553                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1554                                         return 1;
1555                                 }
1556                         }
1557                 }
1558         }
1559
1560         // Make sure we read everything...
1561         if(ferror(f) || !feof(f)) {
1562                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1563                 return 1;
1564         }
1565
1566         if(fclose(f)) {
1567                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1568                 return 1;
1569         }
1570
1571         // Add new variable if necessary.
1572         if(action > 0 || (action == 0 && !set)) {
1573                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1574                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1575                         return 1;
1576                 }
1577         }
1578
1579         if(action < -1) {
1580                 if(!found)
1581                         fprintf(stderr, "No matching configuration variables found.\n");
1582                 return 0;
1583         }
1584
1585         // Make sure we wrote everything...
1586         if(fclose(tf)) {
1587                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1588                 return 1;
1589         }
1590
1591         // Could we find what we had to remove?
1592         if(action < 0 && !removed) {
1593                 remove(tmpfile);
1594                 fprintf(stderr, "No configuration variables deleted.\n");
1595                 return *value;
1596         }
1597
1598         // Replace the configuration file with the new one
1599 #ifdef HAVE_MINGW
1600         if(remove(filename)) {
1601                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1602                 return 1;
1603         }
1604 #endif
1605         if(rename(tmpfile, filename)) {
1606                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1607                 return 1;
1608         }
1609
1610         // Silently try notifying a running tincd of changes.
1611         if(connect_tincd(false))
1612                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1613
1614         return 0;
1615 }
1616
1617 bool check_id(const char *name) {
1618         if(!name || !*name)
1619                 return false;
1620
1621         for(int i = 0; i < strlen(name); i++) {
1622                 if(!isalnum(name[i]) && name[i] != '_')
1623                         return false;
1624         }
1625
1626         return true;
1627 }
1628
1629 static int cmd_init(int argc, char *argv[]) {
1630         if(!access(tinc_conf, F_OK)) {
1631                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1632                 return 1;
1633         }
1634
1635         if(argc > 2) {
1636                 fprintf(stderr, "Too many arguments!\n");
1637                 return 1;
1638         } else if(argc < 2) {
1639                 if(tty) {
1640                         char buf[1024];
1641                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1642                         fflush(stdout);
1643                         if(!fgets(buf, sizeof buf, stdin)) {
1644                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1645                                 return 1;
1646                         }
1647                         int len = rstrip(buf);
1648                         if(!len) {
1649                                 fprintf(stderr, "No name given!\n");
1650                                 return 1;
1651                         }
1652                         name = strdup(buf);
1653                 } else {
1654                         fprintf(stderr, "No Name given!\n");
1655                         return 1;
1656                 }
1657         } else {
1658                 name = strdup(argv[1]);
1659                 if(!*name) {
1660                         fprintf(stderr, "No Name given!\n");
1661                         return 1;
1662                 }
1663         }
1664
1665         if(!check_id(name)) {
1666                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1667                 return 1;
1668         }
1669
1670         if(mkdir(confdir, 0755) && errno != EEXIST) {
1671                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1672                 return 1;
1673         }
1674
1675         if(mkdir(confbase, 0755) && errno != EEXIST) {
1676                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1677                 return 1;
1678         }
1679
1680         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1681                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1682                 return 1;
1683         }
1684
1685         FILE *f = fopen(tinc_conf, "w");
1686         if(!f) {
1687                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1688                 return 1;
1689         }
1690
1691         fprintf(f, "Name = %s\n", name);
1692         fclose(f);
1693
1694         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1695                 return 1;
1696
1697 #ifndef HAVE_MINGW
1698         char *filename;
1699         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1700         if(access(filename, F_OK)) {
1701                 FILE *f = fopen(filename, "w");
1702                 if(!f) {
1703                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1704                         return 1;
1705                 }
1706                 fchmod(fileno(f), 0755);
1707                 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");
1708                 fclose(f);
1709         }
1710 #endif
1711
1712         return 0;
1713
1714 }
1715
1716 static int cmd_generate_keys(int argc, char *argv[]) {
1717         if(argc > 2) {
1718                 fprintf(stderr, "Too many arguments!\n");
1719                 return 1;
1720         }
1721
1722         if(!name)
1723                 name = get_my_name(false);
1724
1725         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1726 }
1727
1728 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1729         if(argc > 2) {
1730                 fprintf(stderr, "Too many arguments!\n");
1731                 return 1;
1732         }
1733
1734         if(!name)
1735                 name = get_my_name(false);
1736
1737         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1738 }
1739
1740 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1741         if(argc > 1) {
1742                 fprintf(stderr, "Too many arguments!\n");
1743                 return 1;
1744         }
1745
1746         if(!name)
1747                 name = get_my_name(false);
1748
1749         return !ecdsa_keygen(true);
1750 }
1751
1752 static int cmd_help(int argc, char *argv[]) {
1753         usage(false);
1754         return 0;
1755 }
1756
1757 static int cmd_version(int argc, char *argv[]) {
1758         if(argc > 1) {
1759                 fprintf(stderr, "Too many arguments!\n");
1760                 return 1;
1761         }
1762
1763         version();
1764         return 0;
1765 }
1766
1767 static int cmd_info(int argc, char *argv[]) {
1768         if(argc != 2) {
1769                 fprintf(stderr, "Invalid number of arguments.\n");
1770                 return 1;
1771         }
1772
1773         if(!connect_tincd(true))
1774                 return 1;
1775
1776         return info(fd, argv[1]);
1777 }
1778
1779 static const char *conffiles[] = {
1780         "tinc.conf",
1781         "tinc-up",
1782         "tinc-down",
1783         "subnet-up",
1784         "subnet-down",
1785         "host-up",
1786         "host-down",
1787         NULL,
1788 };
1789
1790 static int cmd_edit(int argc, char *argv[]) {
1791         if(argc != 2) {
1792                 fprintf(stderr, "Invalid number of arguments.\n");
1793                 return 1;
1794         }
1795
1796         char *filename = NULL;
1797
1798         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1799                 for(int i = 0; conffiles[i]; i++) {
1800                         if(!strcmp(argv[1], conffiles[i])) {
1801                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1802                                 break;
1803                         }
1804                 }
1805         } else {
1806                 argv[1] += 6;
1807         }
1808
1809         if(!filename) {
1810                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1811                 char *dash = strchr(argv[1], '-');
1812                 if(dash) {
1813                         *dash++ = 0;
1814                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1815                                 fprintf(stderr, "Invalid configuration filename.\n");
1816                                 return 1;
1817                         }
1818                 }
1819         }
1820
1821         char *command;
1822 #ifndef HAVE_MINGW
1823         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1824 #else
1825         xasprintf(&command, "edit \"%s\"", filename);
1826 #endif
1827         int result = system(command);
1828         if(result)
1829                 return result;
1830
1831         // Silently try notifying a running tincd of changes.
1832         if(connect_tincd(false))
1833                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1834
1835         return 0;
1836 }
1837
1838 static int export(const char *name, FILE *out) {
1839         char *filename;
1840         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1841         FILE *in = fopen(filename, "r");
1842         if(!in) {
1843                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1844                 return 1;
1845         }
1846
1847         fprintf(out, "Name = %s\n", name);
1848         char buf[4096];
1849         while(fgets(buf, sizeof buf, in)) {
1850                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1851                         fputs(buf, out);
1852         }
1853
1854         if(ferror(in)) {
1855                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1856                 fclose(in);
1857                 return 1;
1858         }
1859
1860         fclose(in);
1861         return 0;
1862 }
1863
1864 static int cmd_export(int argc, char *argv[]) {
1865         if(argc > 1) {
1866                 fprintf(stderr, "Too many arguments!\n");
1867                 return 1;
1868         }
1869
1870         char *name = get_my_name(true);
1871         if(!name)
1872                 return 1;
1873
1874         int result = export(name, stdout);
1875         if(!tty)
1876                 fclose(stdout);
1877
1878         free(name);
1879         return result;
1880 }
1881
1882 static int cmd_export_all(int argc, char *argv[]) {
1883         if(argc > 1) {
1884                 fprintf(stderr, "Too many arguments!\n");
1885                 return 1;
1886         }
1887
1888         DIR *dir = opendir(hosts_dir);
1889         if(!dir) {
1890                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1891                 return 1;
1892         }
1893
1894         bool first = true;
1895         int result = 0;
1896         struct dirent *ent;
1897
1898         while((ent = readdir(dir))) {
1899                 if(!check_id(ent->d_name))
1900                         continue;
1901
1902                 if(first)
1903                         first = false;
1904                 else
1905                         printf("#---------------------------------------------------------------#\n");
1906
1907                 result |= export(ent->d_name, stdout);
1908         }
1909
1910         closedir(dir);
1911         if(!tty)
1912                 fclose(stdout);
1913         return result;
1914 }
1915
1916 static int cmd_import(int argc, char *argv[]) {
1917         if(argc > 1) {
1918                 fprintf(stderr, "Too many arguments!\n");
1919                 return 1;
1920         }
1921
1922         FILE *in = stdin;
1923         FILE *out = NULL;
1924
1925         char buf[4096];
1926         char name[4096];
1927         char *filename = NULL;
1928         int count = 0;
1929         bool firstline = true;
1930
1931         while(fgets(buf, sizeof buf, in)) {
1932                 if(sscanf(buf, "Name = %s", name) == 1) {
1933                         firstline = false;
1934
1935                         if(!check_id(name)) {
1936                                 fprintf(stderr, "Invalid Name in input!\n");
1937                                 return 1;
1938                         }
1939
1940                         if(out)
1941                                 fclose(out);
1942
1943                         free(filename);
1944                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1945
1946                         if(!force && !access(filename, F_OK)) {
1947                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1948                                 out = NULL;
1949                                 continue;
1950                         }
1951
1952                         out = fopen(filename, "w");
1953                         if(!out) {
1954                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1955                                 return 1;
1956                         }
1957
1958                         count++;
1959                         continue;
1960                 } else if(firstline) {
1961                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1962                         firstline = false;
1963                 }
1964
1965
1966                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1967                         continue;
1968
1969                 if(out) {
1970                         if(fputs(buf, out) < 0) {
1971                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1972                                 return 1;
1973                         }
1974                 }
1975         }
1976
1977         if(out)
1978                 fclose(out);
1979
1980         if(count) {
1981                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1982                 return 0;
1983         } else {
1984                 fprintf(stderr, "No host configuration files imported.\n");
1985                 return 1;
1986         }
1987 }
1988
1989 static int cmd_exchange(int argc, char *argv[]) {
1990         return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1991 }
1992
1993 static int cmd_exchange_all(int argc, char *argv[]) {
1994         return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1995 }
1996
1997 static const struct {
1998         const char *command;
1999         int (*function)(int argc, char *argv[]);
2000         bool hidden;
2001 } commands[] = {
2002         {"start", cmd_start},
2003         {"stop", cmd_stop},
2004         {"restart", cmd_restart},
2005         {"reload", cmd_reload},
2006         {"dump", cmd_dump},
2007         {"purge", cmd_purge},
2008         {"debug", cmd_debug},
2009         {"retry", cmd_retry},
2010         {"connect", cmd_connect},
2011         {"disconnect", cmd_disconnect},
2012         {"top", cmd_top},
2013         {"pcap", cmd_pcap},
2014         {"log", cmd_log},
2015         {"pid", cmd_pid},
2016         {"config", cmd_config, true},
2017         {"add", cmd_config},
2018         {"del", cmd_config},
2019         {"get", cmd_config},
2020         {"set", cmd_config},
2021         {"init", cmd_init},
2022         {"generate-keys", cmd_generate_keys},
2023         {"generate-rsa-keys", cmd_generate_rsa_keys},
2024         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
2025         {"help", cmd_help},
2026         {"version", cmd_version},
2027         {"info", cmd_info},
2028         {"edit", cmd_edit},
2029         {"export", cmd_export},
2030         {"export-all", cmd_export_all},
2031         {"import", cmd_import},
2032         {"exchange", cmd_exchange},
2033         {"exchange-all", cmd_exchange_all},
2034         {"invite", cmd_invite},
2035         {"join", cmd_join},
2036         {NULL, NULL},
2037 };
2038
2039 #ifdef HAVE_READLINE
2040 static char *complete_command(const char *text, int state) {
2041         static int i;
2042
2043         if(!state)
2044                 i = 0;
2045         else
2046                 i++;
2047
2048         while(commands[i].command) {
2049                 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2050                         return xstrdup(commands[i].command);
2051                 i++;
2052         }
2053
2054         return NULL;
2055 }
2056
2057 static char *complete_dump(const char *text, int state) {
2058         const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2059         static int i;
2060
2061         if(!state)
2062                 i = 0;
2063         else
2064                 i++;
2065
2066         while(matches[i]) {
2067                 if(!strncasecmp(matches[i], text, strlen(text)))
2068                         return xstrdup(matches[i]);
2069                 i++;
2070         }
2071
2072         return NULL;
2073 }
2074
2075 static char *complete_config(const char *text, int state) {
2076         static int i;
2077
2078         if(!state)
2079                 i = 0;
2080         else
2081                 i++;
2082
2083         while(variables[i].name) {
2084                 char *dot = strchr(text, '.');
2085                 if(dot) {
2086                         if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2087                                 char *match;
2088                                 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2089                                 return match;
2090                         }
2091                 } else {
2092                         if(!strncasecmp(variables[i].name, text, strlen(text)))
2093                                 return xstrdup(variables[i].name);
2094                 }
2095                 i++;
2096         }
2097
2098         return NULL;
2099 }
2100
2101 static char *complete_info(const char *text, int state) {
2102         static int i;
2103         if(!state) {
2104                 i = 0;
2105                 if(!connect_tincd(false))
2106                         return NULL;
2107                 // Check the list of nodes
2108                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2109                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2110         }
2111
2112         while(recvline(fd, line, sizeof line)) {
2113                 char item[4096];
2114                 int n = sscanf(line, "%d %d %s", &code, &req, item);
2115                 if(n == 2) {
2116                         i++;
2117                         if(i >= 2)
2118                                 break;
2119                         else
2120                                 continue;
2121                 }
2122
2123                 if(n != 3) {
2124                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2125                         break;
2126                 }
2127
2128                 if(!strncmp(item, text, strlen(text)))
2129                         return xstrdup(strip_weight(item));
2130         }
2131
2132         return NULL;
2133 }
2134
2135 static char *complete_nothing(const char *text, int state) {
2136         return NULL;
2137 }
2138
2139 static char **completion (const char *text, int start, int end) {
2140         char **matches = NULL;
2141
2142         if(!start)
2143                 matches = rl_completion_matches(text, complete_command);
2144         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2145                 matches = rl_completion_matches(text, complete_dump);
2146         else if(!strncasecmp(rl_line_buffer, "add ", 4))
2147                 matches = rl_completion_matches(text, complete_config);
2148         else if(!strncasecmp(rl_line_buffer, "del ", 4))
2149                 matches = rl_completion_matches(text, complete_config);
2150         else if(!strncasecmp(rl_line_buffer, "get ", 4))
2151                 matches = rl_completion_matches(text, complete_config);
2152         else if(!strncasecmp(rl_line_buffer, "set ", 4))
2153                 matches = rl_completion_matches(text, complete_config);
2154         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2155                 matches = rl_completion_matches(text, complete_info);
2156
2157         return matches;
2158 }
2159 #endif
2160
2161 static int cmd_shell(int argc, char *argv[]) {
2162         char *prompt;
2163         xasprintf(&prompt, "%s> ", identname);
2164         int result = 0;
2165         char buf[4096];
2166         char *line = NULL;
2167         int maxargs = argc + 16;
2168         char **nargv = xmalloc(maxargs * sizeof *nargv);
2169
2170         for(int i = 0; i < argc; i++)
2171                 nargv[i] = argv[i];
2172
2173 #ifdef HAVE_READLINE
2174         rl_readline_name = "tinc";
2175         rl_completion_entry_function = complete_nothing;
2176         rl_attempted_completion_function = completion;
2177         rl_filename_completion_desired = 0;
2178         char *copy = NULL;
2179 #endif
2180
2181         while(true) {
2182 #ifdef HAVE_READLINE
2183                 if(tty) {
2184                         free(copy);
2185                         free(line);
2186                         rl_basic_word_break_characters = "\t\n ";
2187                         line = readline(prompt);
2188                         if(line)
2189                                 copy = xstrdup(line);
2190                 } else {
2191                         line = fgets(buf, sizeof buf, stdin);
2192                 }
2193 #else
2194                 if(tty)
2195                         fputs(prompt, stdout);
2196
2197                 line = fgets(buf, sizeof buf, stdin);
2198 #endif
2199
2200                 if(!line)
2201                         break;
2202
2203                 /* Ignore comments */
2204
2205                 if(*line == '#')
2206                         continue;
2207
2208                 /* Split */
2209
2210                 int nargc = argc;
2211                 char *p = line + strspn(line, " \t\n");
2212                 char *next = strtok(p, " \t\n");
2213
2214                 while(p && *p) {
2215                         if(nargc >= maxargs) {
2216                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2217                                 abort();
2218                                 maxargs *= 2;
2219                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2220                         }
2221
2222                         nargv[nargc++] = p;
2223                         p = next;
2224                         next = strtok(NULL, " \t\n");
2225                 }
2226
2227                 if(nargc == argc)
2228                         continue;
2229
2230                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2231                         return result;
2232
2233                 bool found = false;
2234
2235                 for(int i = 0; commands[i].command; i++) {
2236                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2237                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2238                                 found = true;
2239                                 break;
2240                         }
2241                 }
2242
2243 #ifdef HAVE_READLINE
2244                 if(tty && found)
2245                         add_history(copy);
2246 #endif
2247
2248                 if(!found) {
2249                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2250                         result |= 1;
2251                 }
2252         }
2253
2254         free(nargv);
2255
2256         if(tty)
2257                 printf("\n");
2258         return result;
2259 }
2260
2261
2262 int main(int argc, char *argv[]) {
2263         program_name = argv[0];
2264         orig_argv = argv;
2265         orig_argc = argc;
2266
2267         if(!parse_options(argc, argv))
2268                 return 1;
2269
2270         make_names();
2271         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2272         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2273
2274         if(show_version) {
2275                 version();
2276                 return 0;
2277         }
2278
2279         if(show_help) {
2280                 usage(false);
2281                 return 0;
2282         }
2283
2284         crypto_init();
2285
2286         tty = isatty(0) && isatty(1);
2287
2288         if(optind >= argc)
2289                 return cmd_shell(argc, argv);
2290
2291         for(int i = 0; commands[i].command; i++) {
2292                 if(!strcasecmp(argv[optind], commands[i].command))
2293                         return commands[i].function(argc - optind, argv + optind);
2294         }
2295
2296         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2297         usage(true);
2298         return 1;
2299 }