Releasing 1.1pre5.
[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         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
838                 fprintf(stderr, "Could not stop tinc daemon.\n");
839                 return 1;
840         }
841
842         // Wait for tincd to close the connection...
843         fd_set r;
844         FD_ZERO(&r);
845         FD_SET(fd, &r);
846         select(fd + 1, &r, NULL, NULL, NULL);
847 #else
848         if(!remove_service())
849                 return 1;
850 #endif
851         close(fd);
852         pid = 0;
853         fd = -1;
854
855         return 0;
856 }
857
858 static int cmd_restart(int argc, char *argv[]) {
859         cmd_stop(argc, argv);
860         return cmd_start(argc, argv);
861 }
862
863 static int cmd_reload(int argc, char *argv[]) {
864         if(argc > 1) {
865                 fprintf(stderr, "Too many arguments!\n");
866                 return 1;
867         }
868
869         if(!connect_tincd(true))
870                 return 1;
871
872         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
873         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
874                 fprintf(stderr, "Could not reload configuration.\n");
875                 return 1;
876         }
877
878         return 0;
879
880 }
881
882 static int cmd_dump(int argc, char *argv[]) {
883         bool only_reachable = false;
884
885         if(argc > 2 && !strcasecmp(argv[1], "reachable")) {
886                 if(strcasecmp(argv[2], "nodes")) {
887                         fprintf(stderr, "`reachable' only supported for nodes.\n");
888                         usage(true);
889                         return 1;
890                 }
891                 only_reachable = true;
892                 argv++;
893                 argc--;
894         }
895
896         if(argc != 2) {
897                 fprintf(stderr, "Invalid number of arguments.\n");
898                 usage(true);
899                 return 1;
900         }
901
902         if(!connect_tincd(true))
903                 return 1;
904
905         int do_graph = 0;
906
907         if(!strcasecmp(argv[1], "nodes"))
908                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
909         else if(!strcasecmp(argv[1], "edges"))
910                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
911         else if(!strcasecmp(argv[1], "subnets"))
912                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
913         else if(!strcasecmp(argv[1], "connections"))
914                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
915         else if(!strcasecmp(argv[1], "graph")) {
916                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
917                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
918                 do_graph = 1;
919         } else if(!strcasecmp(argv[1], "digraph")) {
920                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
921                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
922                 do_graph = 2;
923         } else {
924                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[1]);
925                 usage(true);
926                 return 1;
927         }
928
929         if(do_graph == 1)
930                 printf("graph {\n");
931         else if(do_graph == 2)
932                 printf("digraph {\n");
933
934         while(recvline(fd, line, sizeof line)) {
935                 char node1[4096], node2[4096];
936                 int n = sscanf(line, "%d %d %s %s", &code, &req, node1, node2);
937                 if(n == 2) {
938                         if(do_graph && req == REQ_DUMP_NODES)
939                                 continue;
940                         else {
941                                 if(do_graph)
942                                         printf("}\n");
943                                 return 0;
944                         }
945                 }
946                 if(n < 2)
947                         break;
948
949                 char node[4096];
950                 char from[4096];
951                 char to[4096];
952                 char subnet[4096];
953                 char host[4096];
954                 char port[4096];
955                 char via[4096];
956                 char nexthop[4096];
957                 int cipher, digest, maclength, compression, distance, socket, weight;
958                 short int pmtu, minmtu, maxmtu;
959                 unsigned int options, status_int;
960                 node_status_t status;
961                 long int last_state_change;
962
963                 switch(req) {
964                         case REQ_DUMP_NODES: {
965                                 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);
966                                 if(n != 16) {
967                                         fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
968                                         return 1;
969                                 }
970
971                                 memcpy(&status, &status_int, sizeof status);
972
973                                 if(do_graph) {
974                                         const char *color = "black";
975                                         if(!strcmp(host, "MYSELF"))
976                                                 color = "green";
977                                         else if(!status.reachable)
978                                                 color = "red";
979                                         else if(strcmp(via, node))
980                                                 color = "orange";
981                                         else if(!status.validkey)
982                                                 color = "black";
983                                         else if(minmtu > 0)
984                                                 color = "green";
985                                         printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
986                                 } else {
987                                         if(only_reachable && !status.reachable)
988                                                 continue;
989                                         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",
990                                                         node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
991                                 }
992                         } break;
993
994                         case REQ_DUMP_EDGES: {
995                                 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
996                                 if(n != 6) {
997                                         fprintf(stderr, "Unable to parse edge dump from tincd.\n");
998                                         return 1;
999                                 }
1000
1001                                 if(do_graph) {
1002                                         float w = 1 + 65536.0 / weight;
1003                                         if(do_graph == 1 && strcmp(node1, node2) > 0)
1004                                                 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1005                                         else if(do_graph == 2)
1006                                                 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1007                                 } else {
1008                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1009                                 }
1010                         } break;
1011
1012                         case REQ_DUMP_SUBNETS: {
1013                                 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1014                                 if(n != 2) {
1015                                         fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1016                                         return 1;
1017                                 }
1018                                 printf("%s owner %s\n", strip_weight(subnet), node);
1019                         } break;
1020
1021                         case REQ_DUMP_CONNECTIONS: {
1022                                 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1023                                 if(n != 6) {
1024                                         fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1025                                         return 1;
1026                                 }
1027                                 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1028                         } break;
1029
1030                         default:
1031                                 fprintf(stderr, "Unable to parse dump from tincd.\n");
1032                                 return 1;
1033                 }
1034         }
1035
1036         fprintf(stderr, "Error receiving dump.\n");
1037         return 1;
1038 }
1039
1040 static int cmd_purge(int argc, char *argv[]) {
1041         if(argc > 1) {
1042                 fprintf(stderr, "Too many arguments!\n");
1043                 return 1;
1044         }
1045
1046         if(!connect_tincd(true))
1047                 return 1;
1048
1049         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1050         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1051                 fprintf(stderr, "Could not purge old information.\n");
1052                 return 1;
1053         }
1054
1055         return 0;
1056 }
1057
1058 static int cmd_debug(int argc, char *argv[]) {
1059         if(argc != 2) {
1060                 fprintf(stderr, "Invalid number of arguments.\n");
1061                 return 1;
1062         }
1063
1064         if(!connect_tincd(true))
1065                 return 1;
1066
1067         int debuglevel = atoi(argv[1]);
1068         int origlevel;
1069
1070         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1071         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1072                 fprintf(stderr, "Could not set debug level.\n");
1073                 return 1;
1074         }
1075
1076         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1077         return 0;
1078 }
1079
1080 static int cmd_retry(int argc, char *argv[]) {
1081         if(argc > 1) {
1082                 fprintf(stderr, "Too many arguments!\n");
1083                 return 1;
1084         }
1085
1086         if(!connect_tincd(true))
1087                 return 1;
1088
1089         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1090         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1091                 fprintf(stderr, "Could not retry outgoing connections.\n");
1092                 return 1;
1093         }
1094
1095         return 0;
1096 }
1097
1098 static int cmd_connect(int argc, char *argv[]) {
1099         if(argc != 2) {
1100                 fprintf(stderr, "Invalid number of arguments.\n");
1101                 return 1;
1102         }
1103
1104         if(!check_id(argv[1])) {
1105                 fprintf(stderr, "Invalid name for node.\n");
1106                 return 1;
1107         }
1108
1109         if(!connect_tincd(true))
1110                 return 1;
1111
1112         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1113         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1114                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1115                 return 1;
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int cmd_disconnect(int argc, char *argv[]) {
1122         if(argc != 2) {
1123                 fprintf(stderr, "Invalid number of arguments.\n");
1124                 return 1;
1125         }
1126
1127         if(!check_id(argv[1])) {
1128                 fprintf(stderr, "Invalid name for node.\n");
1129                 return 1;
1130         }
1131
1132         if(!connect_tincd(true))
1133                 return 1;
1134
1135         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1136         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1137                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1138                 return 1;
1139         }
1140
1141         return 0;
1142 }
1143
1144 static int cmd_top(int argc, char *argv[]) {
1145         if(argc > 1) {
1146                 fprintf(stderr, "Too many arguments!\n");
1147                 return 1;
1148         }
1149
1150 #ifdef HAVE_CURSES
1151         if(!connect_tincd(true))
1152                 return 1;
1153
1154         top(fd);
1155         return 0;
1156 #else
1157         fprintf(stderr, "This version of tincctl was compiled without support for the curses library.\n");
1158         return 1;
1159 #endif
1160 }
1161
1162 static int cmd_pcap(int argc, char *argv[]) {
1163         if(argc > 2) {
1164                 fprintf(stderr, "Too many arguments!\n");
1165                 return 1;
1166         }
1167
1168         if(!connect_tincd(true))
1169                 return 1;
1170
1171         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1172         return 0;
1173 }
1174
1175 static int cmd_log(int argc, char *argv[]) {
1176         if(argc > 2) {
1177                 fprintf(stderr, "Too many arguments!\n");
1178                 return 1;
1179         }
1180
1181         if(!connect_tincd(true))
1182                 return 1;
1183
1184         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1185         return 0;
1186 }
1187
1188 static int cmd_pid(int argc, char *argv[]) {
1189         if(argc > 1) {
1190                 fprintf(stderr, "Too many arguments!\n");
1191                 return 1;
1192         }
1193
1194         if(!connect_tincd(true) && !pid)
1195                 return 1;
1196
1197         printf("%d\n", pid);
1198         return 0;
1199 }
1200
1201 static int rstrip(char *value) {
1202         int len = strlen(value);
1203         while(len && strchr("\t\r\n ", value[len - 1]))
1204                 value[--len] = 0;
1205         return len;
1206 }
1207
1208 static char *get_my_name() {
1209         FILE *f = fopen(tinc_conf, "r");
1210         if(!f) {
1211                 fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1212                 return NULL;
1213         }
1214
1215         char buf[4096];
1216         char *value;
1217         while(fgets(buf, sizeof buf, f)) {
1218                 int len = strcspn(buf, "\t =");
1219                 value = buf + len;
1220                 value += strspn(value, "\t ");
1221                 if(*value == '=') {
1222                         value++;
1223                         value += strspn(value, "\t ");
1224                 }
1225                 if(!rstrip(value))
1226                         continue;
1227                 buf[len] = 0;
1228                 if(strcasecmp(buf, "Name"))
1229                         continue;
1230                 if(*value) {
1231                         fclose(f);
1232                         return strdup(value);
1233                 }
1234         }
1235
1236         fclose(f);
1237         fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1238         return NULL;
1239 }
1240
1241 #define VAR_SERVER 1    /* Should be in tinc.conf */
1242 #define VAR_HOST 2      /* Can be in host config file */
1243 #define VAR_MULTIPLE 4  /* Multiple statements allowed */
1244 #define VAR_OBSOLETE 8  /* Should not be used anymore */
1245
1246 static struct {
1247         const char *name;
1248         int type;
1249 } const variables[] = {
1250         /* Server configuration */
1251         {"AddressFamily", VAR_SERVER},
1252         {"AutoConnect", VAR_SERVER},
1253         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1254         {"BindToInterface", VAR_SERVER},
1255         {"Broadcast", VAR_SERVER},
1256         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE},
1257         {"DecrementTTL", VAR_SERVER},
1258         {"Device", VAR_SERVER},
1259         {"DeviceType", VAR_SERVER},
1260         {"DirectOnly", VAR_SERVER},
1261         {"ECDSAPrivateKeyFile", VAR_SERVER},
1262         {"ExperimentalProtocol", VAR_SERVER},
1263         {"Forwarding", VAR_SERVER},
1264         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1265         {"Hostnames", VAR_SERVER},
1266         {"IffOneQueue", VAR_SERVER},
1267         {"Interface", VAR_SERVER},
1268         {"KeyExpire", VAR_SERVER},
1269         {"LocalDiscovery", VAR_SERVER},
1270         {"MACExpire", VAR_SERVER},
1271         {"MaxOutputBufferSize", VAR_SERVER},
1272         {"MaxTimeout", VAR_SERVER},
1273         {"Mode", VAR_SERVER},
1274         {"Name", VAR_SERVER},
1275         {"PingInterval", VAR_SERVER},
1276         {"PingTimeout", VAR_SERVER},
1277         {"PriorityInheritance", VAR_SERVER},
1278         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1279         {"PrivateKeyFile", VAR_SERVER},
1280         {"ProcessPriority", VAR_SERVER},
1281         {"Proxy", VAR_SERVER},
1282         {"ReplayWindow", VAR_SERVER},
1283         {"ScriptsExtension", VAR_SERVER},
1284         {"ScriptsInterpreter", VAR_SERVER},
1285         {"StrictSubnets", VAR_SERVER},
1286         {"TunnelServer", VAR_SERVER},
1287         {"UDPRcvBuf", VAR_SERVER},
1288         {"UDPSndBuf", VAR_SERVER},
1289         {"VDEGroup", VAR_SERVER},
1290         {"VDEPort", VAR_SERVER},
1291         /* Host configuration */
1292         {"Address", VAR_HOST | VAR_MULTIPLE},
1293         {"Cipher", VAR_SERVER | VAR_HOST},
1294         {"ClampMSS", VAR_SERVER | VAR_HOST},
1295         {"Compression", VAR_SERVER | VAR_HOST},
1296         {"Digest", VAR_SERVER | VAR_HOST},
1297         {"ECDSAPublicKey", VAR_HOST},
1298         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
1299         {"IndirectData", VAR_SERVER | VAR_HOST},
1300         {"MACLength", VAR_SERVER | VAR_HOST},
1301         {"PMTU", VAR_SERVER | VAR_HOST},
1302         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1303         {"Port", VAR_HOST},
1304         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1305         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1306         {"Subnet", VAR_HOST | VAR_MULTIPLE},
1307         {"TCPOnly", VAR_SERVER | VAR_HOST},
1308         {"Weight", VAR_HOST},
1309         {NULL, 0}
1310 };
1311
1312 static int cmd_config(int argc, char *argv[]) {
1313         if(argc < 2) {
1314                 fprintf(stderr, "Invalid number of arguments.\n");
1315                 return 1;
1316         }
1317
1318         int action = -2;
1319         if(!strcasecmp(argv[1], "get")) {
1320                 argv++, argc--;
1321         } else if(!strcasecmp(argv[1], "add")) {
1322                 argv++, argc--, action = 1;
1323         } else if(!strcasecmp(argv[1], "del")) {
1324                 argv++, argc--, action = -1;
1325         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1326                 argv++, argc--, action = 0;
1327         }
1328
1329         if(argc < 2) {
1330                 fprintf(stderr, "Invalid number of arguments.\n");
1331                 return 1;
1332         }
1333
1334         // Concatenate the rest of the command line
1335         strncpy(line, argv[1], sizeof line - 1);
1336         for(int i = 2; i < argc; i++) {
1337                 strncat(line, " ", sizeof line - 1 - strlen(line));
1338                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1339         }
1340
1341         // Liberal parsing into node name, variable name and value.
1342         char *node = NULL;
1343         char *variable;
1344         char *value;
1345         int len;
1346
1347         len = strcspn(line, "\t =");
1348         value = line + len;
1349         value += strspn(value, "\t ");
1350         if(*value == '=') {
1351                 value++;
1352                 value += strspn(value, "\t ");
1353         }
1354         line[len] = '\0';
1355         variable = strchr(line, '.');
1356         if(variable) {
1357                 node = line;
1358                 *variable++ = 0;
1359         } else {
1360                 variable = line;
1361         }
1362
1363         if(!*variable) {
1364                 fprintf(stderr, "No variable given.\n");
1365                 return 1;
1366         }
1367
1368         if(action >= 0 && !*value) {
1369                 fprintf(stderr, "No value for variable given.\n");
1370                 return 1;
1371         }
1372
1373         if(action < -1 && *value)
1374                 action = 0;
1375
1376         /* Some simple checks. */
1377         bool found = false;
1378
1379         for(int i = 0; variables[i].name; i++) {
1380                 if(strcasecmp(variables[i].name, variable))
1381                         continue;
1382
1383                 found = true;
1384                 variable = (char *)variables[i].name;
1385
1386                 /* Discourage use of obsolete variables. */
1387
1388                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1389                         if(force) {
1390                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1391                         } else {
1392                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1393                                 return 1;
1394                         }
1395                 }
1396
1397                 /* Don't put server variables in host config files */
1398
1399                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1400                         if(force) {
1401                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1402                         } else {
1403                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1404                                 return 1;
1405                         }
1406                 }
1407
1408                 /* Should this go into our own host config file? */
1409
1410                 if(!node && !(variables[i].type & VAR_SERVER)) {
1411                         node = get_my_name();
1412                         if(!node)
1413                                 return 1;
1414                 }
1415
1416                 break;
1417         }
1418
1419         if(node && !check_id(node)) {
1420                 fprintf(stderr, "Invalid name for node.\n");
1421                 return 1;
1422         }
1423
1424         if(!found) {
1425                 if(force || action < 0) {
1426                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1427                 } else {
1428                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1429                         return 1;
1430                 }
1431         }
1432
1433         // Open the right configuration file.
1434         char *filename;
1435         if(node)
1436                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1437         else
1438                 filename = tinc_conf;
1439
1440         FILE *f = fopen(filename, "r");
1441         if(!f) {
1442                 if(action < 0 || errno != ENOENT) {
1443                         fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1444                         return 1;
1445                 }
1446
1447                 // If it doesn't exist, create it.
1448                 f = fopen(filename, "a+");
1449                 if(!f) {
1450                         fprintf(stderr, "Could not create configuration file %s: %s\n", filename, strerror(errno));
1451                         return 1;
1452                 } else {
1453                         fprintf(stderr, "Created configuration file %s.\n", filename);
1454                 }
1455         }
1456
1457         char *tmpfile = NULL;
1458         FILE *tf = NULL;
1459
1460         if(action >= -1) {
1461                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1462                 tf = fopen(tmpfile, "w");
1463                 if(!tf) {
1464                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1465                         fclose(f);
1466                         return 1;
1467                 }
1468         }
1469
1470         // Copy the file, making modifications on the fly, unless we are just getting a value.
1471         char buf1[4096];
1472         char buf2[4096];
1473         bool set = false;
1474         bool removed = false;
1475         found = false;
1476
1477         while(fgets(buf1, sizeof buf1, f)) {
1478                 buf1[sizeof buf1 - 1] = 0;
1479                 strncpy(buf2, buf1, sizeof buf2);
1480
1481                 // Parse line in a simple way
1482                 char *bvalue;
1483                 int len;
1484
1485                 len = strcspn(buf2, "\t =");
1486                 bvalue = buf2 + len;
1487                 bvalue += strspn(bvalue, "\t ");
1488                 if(*bvalue == '=') {
1489                         bvalue++;
1490                         bvalue += strspn(bvalue, "\t ");
1491                 }
1492                 rstrip(bvalue);
1493                 buf2[len] = '\0';
1494
1495                 // Did it match?
1496                 if(!strcasecmp(buf2, variable)) {
1497                         // Get
1498                         if(action < -1) {
1499                                 found = true;
1500                                 printf("%s\n", bvalue);
1501                         // Del
1502                         } else if(action == -1) {
1503                                 if(!*value || !strcasecmp(bvalue, value)) {
1504                                         removed = true;
1505                                         continue;
1506                                 }
1507                         // Set
1508                         } else if(action == 0) {
1509                                 // Already set? Delete the rest...
1510                                 if(set)
1511                                         continue;
1512                                 // Otherwise, replace.
1513                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1514                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1515                                         return 1;
1516                                 }
1517                                 set = true;
1518                                 continue;
1519                         }
1520                 }
1521
1522                 if(action >= -1) {
1523                         // Copy original line...
1524                         if(fputs(buf1, tf) < 0) {
1525                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1526                                 return 1;
1527                         }
1528
1529                         // Add newline if it is missing...
1530                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1531                                 if(fputc('\n', tf) < 0) {
1532                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1533                                         return 1;
1534                                 }
1535                         }
1536                 }
1537         }
1538
1539         // Make sure we read everything...
1540         if(ferror(f) || !feof(f)) {
1541                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1542                 return 1;
1543         }
1544
1545         if(fclose(f)) {
1546                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1547                 return 1;
1548         }
1549
1550         // Add new variable if necessary.
1551         if(action > 0 || (action == 0 && !set)) {
1552                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1553                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1554                         return 1;
1555                 }
1556         }
1557
1558         if(action < -1) {
1559                 if(!found)
1560                         fprintf(stderr, "No matching configuration variables found.\n");
1561                 return 0;
1562         }
1563
1564         // Make sure we wrote everything...
1565         if(fclose(tf)) {
1566                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1567                 return 1;
1568         }
1569
1570         // Could we find what we had to remove?
1571         if(action < 0 && !removed) {
1572                 remove(tmpfile);
1573                 fprintf(stderr, "No configuration variables deleted.\n");
1574                 return *value;
1575         }
1576
1577         // Replace the configuration file with the new one
1578 #ifdef HAVE_MINGW
1579         if(remove(filename)) {
1580                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1581                 return 1;
1582         }
1583 #endif
1584         if(rename(tmpfile, filename)) {
1585                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1586                 return 1;
1587         }
1588
1589         // Silently try notifying a running tincd of changes.
1590         if(connect_tincd(false))
1591                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1592
1593         return 0;
1594 }
1595
1596 bool check_id(const char *name) {
1597         if(!name || !*name)
1598                 return false;
1599
1600         for(int i = 0; i < strlen(name); i++) {
1601                 if(!isalnum(name[i]) && name[i] != '_')
1602                         return false;
1603         }
1604
1605         return true;
1606 }
1607
1608 static int cmd_init(int argc, char *argv[]) {
1609         if(!access(tinc_conf, F_OK)) {
1610                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1611                 return 1;
1612         }
1613
1614         if(argc > 2) {
1615                 fprintf(stderr, "Too many arguments!\n");
1616                 return 1;
1617         } else if(argc < 2) {
1618                 if(tty) {
1619                         char buf[1024];
1620                         fprintf(stdout, "Enter the Name you want your tinc node to have: ");
1621                         fflush(stdout);
1622                         if(!fgets(buf, sizeof buf, stdin)) {
1623                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1624                                 return 1;
1625                         }
1626                         int len = rstrip(buf);
1627                         if(!len) {
1628                                 fprintf(stderr, "No name given!\n");
1629                                 return 1;
1630                         }
1631                         name = strdup(buf);
1632                 } else {
1633                         fprintf(stderr, "No Name given!\n");
1634                         return 1;
1635                 }
1636         } else {
1637                 name = strdup(argv[1]);
1638                 if(!*name) {
1639                         fprintf(stderr, "No Name given!\n");
1640                         return 1;
1641                 }
1642         }
1643
1644         if(!check_id(name)) {
1645                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1646                 return 1;
1647         }
1648
1649         if(mkdir(confdir, 0755) && errno != EEXIST) {
1650                 fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
1651                 return 1;
1652         }
1653
1654         if(mkdir(confbase, 0755) && errno != EEXIST) {
1655                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1656                 return 1;
1657         }
1658
1659         if(mkdir(hosts_dir, 0755) && errno != EEXIST) {
1660                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1661                 return 1;
1662         }
1663
1664         FILE *f = fopen(tinc_conf, "w");
1665         if(!f) {
1666                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1667                 return 1;
1668         }
1669
1670         fprintf(f, "Name = %s\n", name);
1671         fclose(f);
1672
1673         if(!rsa_keygen(2048, false) || !ecdsa_keygen(false))
1674                 return 1;
1675
1676 #ifndef HAVE_MINGW
1677         char *filename;
1678         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1679         if(access(filename, F_OK)) {
1680                 FILE *f = fopen(filename, "w");
1681                 if(!f) {
1682                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1683                         return 1;
1684                 }
1685                 fchmod(fileno(f), 0755);
1686                 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");
1687                 fclose(f);
1688         }
1689 #endif
1690
1691         return 0;
1692
1693 }
1694
1695 static int cmd_generate_keys(int argc, char *argv[]) {
1696         if(argc > 2) {
1697                 fprintf(stderr, "Too many arguments!\n");
1698                 return 1;
1699         }
1700
1701         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ecdsa_keygen(true));
1702 }
1703
1704 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1705         if(argc > 2) {
1706                 fprintf(stderr, "Too many arguments!\n");
1707                 return 1;
1708         }
1709
1710         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1711 }
1712
1713 static int cmd_generate_ecdsa_keys(int argc, char *argv[]) {
1714         if(argc > 1) {
1715                 fprintf(stderr, "Too many arguments!\n");
1716                 return 1;
1717         }
1718
1719         return !ecdsa_keygen(true);
1720 }
1721
1722 static int cmd_help(int argc, char *argv[]) {
1723         usage(false);
1724         return 0;
1725 }
1726
1727 static int cmd_version(int argc, char *argv[]) {
1728         if(argc > 1) {
1729                 fprintf(stderr, "Too many arguments!\n");
1730                 return 1;
1731         }
1732
1733         version();
1734         return 0;
1735 }
1736
1737 static int cmd_info(int argc, char *argv[]) {
1738         if(argc != 2) {
1739                 fprintf(stderr, "Invalid number of arguments.\n");
1740                 return 1;
1741         }
1742
1743         if(!connect_tincd(true))
1744                 return 1;
1745
1746         return info(fd, argv[1]);
1747 }
1748
1749 static const char *conffiles[] = {
1750         "tinc.conf",
1751         "tinc-up",
1752         "tinc-down",
1753         "subnet-up",
1754         "subnet-down",
1755         "host-up",
1756         "host-down",
1757         NULL,
1758 };
1759
1760 static int cmd_edit(int argc, char *argv[]) {
1761         if(argc != 2) {
1762                 fprintf(stderr, "Invalid number of arguments.\n");
1763                 return 1;
1764         }
1765
1766         char *filename = NULL;
1767
1768         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1769                 for(int i = 0; conffiles[i]; i++) {
1770                         if(!strcmp(argv[1], conffiles[i])) {
1771                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1772                                 break;
1773                         }
1774                 }
1775         } else {
1776                 argv[1] += 6;
1777         }
1778
1779         if(!filename) {
1780                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1781                 char *dash = strchr(argv[1], '-');
1782                 if(dash) {
1783                         *dash++ = 0;
1784                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1785                                 fprintf(stderr, "Invalid configuration filename.\n");
1786                                 return 1;
1787                         }
1788                 }
1789         }
1790
1791         char *command;
1792 #ifndef HAVE_MINGW
1793         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1794 #else
1795         xasprintf(&command, "edit \"%s\"", filename);
1796 #endif
1797         int result = system(command);
1798         if(result)
1799                 return result;
1800
1801         // Silently try notifying a running tincd of changes.
1802         if(connect_tincd(false))
1803                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1804
1805         return 0;
1806 }
1807
1808 static int export(const char *name, FILE *out) {
1809         char *filename;
1810         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1811         FILE *in = fopen(filename, "r");
1812         if(!in) {
1813                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1814                 return 1;
1815         }
1816
1817         fprintf(out, "Name = %s\n", name);
1818         char buf[4096];
1819         while(fgets(buf, sizeof buf, in)) {
1820                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1821                         fputs(buf, out);
1822         }
1823
1824         if(ferror(in)) {
1825                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1826                 fclose(in);
1827                 return 1;
1828         }
1829
1830         fclose(in);
1831         return 0;
1832 }
1833
1834 static int cmd_export(int argc, char *argv[]) {
1835         if(argc > 1) {
1836                 fprintf(stderr, "Too many arguments!\n");
1837                 return 1;
1838         }
1839
1840         char *name = get_my_name();
1841         if(!name)
1842                 return 1;
1843
1844         int result = export(name, stdout);
1845         if(!tty)
1846                 fclose(stdout);
1847         return result;
1848 }
1849
1850 static int cmd_export_all(int argc, char *argv[]) {
1851         if(argc > 1) {
1852                 fprintf(stderr, "Too many arguments!\n");
1853                 return 1;
1854         }
1855
1856         DIR *dir = opendir(hosts_dir);
1857         if(!dir) {
1858                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1859                 return 1;
1860         }
1861
1862         bool first = true;
1863         int result = 0;
1864         struct dirent *ent;
1865
1866         while((ent = readdir(dir))) {
1867                 if(!check_id(ent->d_name))
1868                         continue;
1869
1870                 if(first)
1871                         first = false;
1872                 else
1873                         printf("#---------------------------------------------------------------#\n");
1874
1875                 result |= export(ent->d_name, stdout);
1876         }
1877
1878         closedir(dir);
1879         if(!tty)
1880                 fclose(stdout);
1881         return result;
1882 }
1883
1884 static int cmd_import(int argc, char *argv[]) {
1885         if(argc > 1) {
1886                 fprintf(stderr, "Too many arguments!\n");
1887                 return 1;
1888         }
1889
1890         FILE *in = stdin;
1891         FILE *out = NULL;
1892
1893         char buf[4096];
1894         char name[4096];
1895         char *filename = NULL;
1896         int count = 0;
1897         bool firstline = true;
1898
1899         while(fgets(buf, sizeof buf, in)) {
1900                 if(sscanf(buf, "Name = %s", name) == 1) {
1901                         firstline = false;
1902
1903                         if(!check_id(name)) {
1904                                 fprintf(stderr, "Invalid Name in input!\n");
1905                                 return 1;
1906                         }
1907
1908                         if(out)
1909                                 fclose(out);
1910
1911                         free(filename);
1912                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1913
1914                         if(!force && !access(filename, F_OK)) {
1915                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
1916                                 out = NULL;
1917                                 continue;
1918                         }
1919
1920                         out = fopen(filename, "w");
1921                         if(!out) {
1922                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
1923                                 return 1;
1924                         }
1925
1926                         count++;
1927                         continue;
1928                 } else if(firstline) {
1929                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
1930                         firstline = false;
1931                 }
1932
1933
1934                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
1935                         continue;
1936
1937                 if(out) {
1938                         if(fputs(buf, out) < 0) {
1939                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
1940                                 return 1;
1941                         }
1942                 }
1943         }
1944
1945         if(out)
1946                 fclose(out);
1947
1948         if(count) {
1949                 fprintf(stderr, "Imported %d host configuration files.\n", count);
1950                 return 0;
1951         } else {
1952                 fprintf(stderr, "No host configuration files imported.\n");
1953                 return 1;
1954         }
1955 }
1956
1957 static int cmd_exchange(int argc, char *argv[]) {
1958         return cmd_export(argc, argv) ?: cmd_import(argc, argv);
1959 }
1960
1961 static int cmd_exchange_all(int argc, char *argv[]) {
1962         return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
1963 }
1964
1965 static const struct {
1966         const char *command;
1967         int (*function)(int argc, char *argv[]);
1968 } commands[] = {
1969         {"start", cmd_start},
1970         {"stop", cmd_stop},
1971         {"restart", cmd_restart},
1972         {"reload", cmd_reload},
1973         {"dump", cmd_dump},
1974         {"purge", cmd_purge},
1975         {"debug", cmd_debug},
1976         {"retry", cmd_retry},
1977         {"connect", cmd_connect},
1978         {"disconnect", cmd_disconnect},
1979         {"top", cmd_top},
1980         {"pcap", cmd_pcap},
1981         {"log", cmd_log},
1982         {"pid", cmd_pid},
1983         {"config", cmd_config},
1984         {"init", cmd_init},
1985         {"generate-keys", cmd_generate_keys},
1986         {"generate-rsa-keys", cmd_generate_rsa_keys},
1987         {"generate-ecdsa-keys", cmd_generate_ecdsa_keys},
1988         {"help", cmd_help},
1989         {"version", cmd_version},
1990         {"info", cmd_info},
1991         {"edit", cmd_edit},
1992         {"export", cmd_export},
1993         {"export-all", cmd_export_all},
1994         {"import", cmd_import},
1995         {"exchange", cmd_exchange},
1996         {"exchange-all", cmd_exchange_all},
1997         {NULL, NULL},
1998 };
1999
2000 #ifdef HAVE_READLINE
2001 static char *complete_command(const char *text, int state) {
2002         static int i;
2003
2004         if(!state)
2005                 i = 0;
2006         else
2007                 i++;
2008
2009         while(commands[i].command) {
2010                 if(!strncasecmp(commands[i].command, text, strlen(text)))
2011                         return xstrdup(commands[i].command);
2012                 i++;
2013         }
2014
2015         return NULL;
2016 }
2017
2018 static char *complete_dump(const char *text, int state) {
2019         const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2020         static int i;
2021
2022         if(!state)
2023                 i = 0;
2024         else
2025                 i++;
2026
2027         while(matches[i]) {
2028                 if(!strncasecmp(matches[i], text, strlen(text)))
2029                         return xstrdup(matches[i]);
2030                 i++;
2031         }
2032
2033         return NULL;
2034 }
2035
2036 static char *complete_config(const char *text, int state) {
2037         const char *sub[] = {"get", "set", "add", "del"};
2038         static int i;
2039         if(!state) {
2040                 i = 0;
2041                 if(!strchr(rl_line_buffer + 7, ' '))
2042                         i = -4;
2043                 else {
2044                         bool found = false;
2045                         for(int i = 0; i < 4; i++) {
2046                                 if(!strncasecmp(rl_line_buffer + 7, sub[i], strlen(sub[i])) && rl_line_buffer[7 + strlen(sub[i])] == ' ') {
2047                                         found = true;
2048                                         break;
2049                                 }
2050                         }
2051                         if(!found)
2052                                 return NULL;
2053                 }
2054         } else {
2055                 i++;
2056         }
2057
2058         while(i < 0 || variables[i].name) {
2059                 if(i < 0 && !strncasecmp(sub[i + 4], text, strlen(text)))
2060                         return xstrdup(sub[i + 4]);
2061                 if(i >= 0) {
2062                         char *dot = strchr(text, '.');
2063                         if(dot) {
2064                                 if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2065                                         char *match;
2066                                         xasprintf(&match, "%.*s.%s", dot - text, text, variables[i].name);
2067                                         return match;
2068                                 }
2069                         } else {
2070                                 if(!strncasecmp(variables[i].name, text, strlen(text)))
2071                                         return xstrdup(variables[i].name);
2072                         }
2073                 }
2074                 i++;
2075         }
2076
2077         return NULL;
2078 }
2079
2080 static char *complete_info(const char *text, int state) {
2081         static int i;
2082         if(!state) {
2083                 i = 0;
2084                 if(!connect_tincd(false))
2085                         return NULL;
2086                 // Check the list of nodes
2087                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2088                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2089         }
2090
2091         while(recvline(fd, line, sizeof line)) {
2092                 char item[4096];
2093                 int n = sscanf(line, "%d %d %s", &code, &req, item);
2094                 if(n == 2) {
2095                         i++;
2096                         if(i >= 2)
2097                                 break;
2098                         else
2099                                 continue;
2100                 }
2101
2102                 if(n != 3) {
2103                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2104                         break;
2105                 }
2106
2107                 if(!strncmp(item, text, strlen(text)))
2108                         return xstrdup(strip_weight(item));
2109         }
2110
2111         return NULL;
2112 }
2113
2114 static char *complete_nothing(const char *text, int state) {
2115         return NULL;
2116 }
2117
2118 static char **completion (const char *text, int start, int end) {
2119         char **matches = NULL;
2120
2121         if(!start)
2122                 matches = rl_completion_matches(text, complete_command);
2123         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2124                 matches = rl_completion_matches(text, complete_dump);
2125         else if(!strncasecmp(rl_line_buffer, "config ", 7))
2126                 matches = rl_completion_matches(text, complete_config);
2127         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2128                 matches = rl_completion_matches(text, complete_info);
2129
2130         return matches;
2131 }
2132 #endif
2133
2134 static int cmd_shell(int argc, char *argv[]) {
2135         char *prompt;
2136         xasprintf(&prompt, "%s> ", identname);
2137         int result = 0;
2138         char buf[4096];
2139         char *line = NULL;
2140         int maxargs = argc + 16;
2141         char **nargv = xmalloc(maxargs * sizeof *nargv);
2142
2143         for(int i = 0; i < argc; i++)
2144                 nargv[i] = argv[i];
2145
2146 #ifdef HAVE_READLINE
2147         rl_readline_name = "tinc";
2148         rl_completion_entry_function = complete_nothing;
2149         rl_attempted_completion_function = completion;
2150         rl_filename_completion_desired = 0;
2151         char *copy = NULL;
2152 #endif
2153
2154         while(true) {
2155 #ifdef HAVE_READLINE
2156                 if(tty) {
2157                         free(copy);
2158                         free(line);
2159                         rl_basic_word_break_characters = "\t\n ";
2160                         line = readline(prompt);
2161                         if(line)
2162                                 copy = xstrdup(line);
2163                 } else {
2164                         line = fgets(buf, sizeof buf, stdin);
2165                 }
2166 #else
2167                 if(tty)
2168                         fputs(prompt, stdout);
2169
2170                 line = fgets(buf, sizeof buf, stdin);
2171 #endif
2172
2173                 if(!line)
2174                         break;
2175
2176                 /* Ignore comments */
2177
2178                 if(*line == '#')
2179                         continue;
2180
2181                 /* Split */
2182
2183                 int nargc = argc;
2184                 char *p = line + strspn(line, " \t\n");
2185                 char *next = strtok(p, " \t\n");
2186
2187                 while(p && *p) {
2188                         if(nargc >= maxargs) {
2189                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2190                                 abort();
2191                                 maxargs *= 2;
2192                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2193                         }
2194
2195                         nargv[nargc++] = p;
2196                         p = next;
2197                         next = strtok(NULL, " \t\n");
2198                 }
2199
2200                 if(nargc == argc)
2201                         continue;
2202
2203                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2204                         return result;
2205
2206                 bool found = false;
2207
2208                 for(int i = 0; commands[i].command; i++) {
2209                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2210                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2211                                 found = true;
2212                                 break;
2213                         }
2214                 }
2215
2216 #ifdef HAVE_READLINE
2217                 if(tty && found)
2218                         add_history(copy);
2219 #endif
2220
2221                 if(!found) {
2222                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2223                         result |= 1;
2224                 }
2225         }
2226
2227         free(nargv);
2228
2229         if(tty)
2230                 printf("\n");
2231         return result;
2232 }
2233
2234
2235 int main(int argc, char *argv[]) {
2236         program_name = argv[0];
2237         orig_argv = argv;
2238         orig_argc = argc;
2239
2240         if(!parse_options(argc, argv))
2241                 return 1;
2242
2243         make_names();
2244         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2245         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2246
2247         if(show_version) {
2248                 version();
2249                 return 0;
2250         }
2251
2252         if(show_help) {
2253                 usage(false);
2254                 return 0;
2255         }
2256
2257         tty = isatty(0) && isatty(1);
2258
2259         if(optind >= argc)
2260                 return cmd_shell(argc, argv);
2261
2262         for(int i = 0; commands[i].command; i++) {
2263                 if(!strcasecmp(argv[optind], commands[i].command))
2264                         return commands[i].function(argc - optind, argv + optind);
2265         }
2266
2267         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2268         usage(true);
2269         return 1;
2270 }