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