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