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