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