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