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