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