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