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