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