da66c8ffb441d931810c643cf887613689fefc6e
[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 via[4096];
989                 char nexthop[4096];
990                 int cipher, digest, maclength, compression, distance, socket, weight;
991                 short int pmtu, minmtu, maxmtu;
992                 unsigned int options, status_int;
993                 node_status_t status;
994                 long int last_state_change;
995
996                 switch(req) {
997                         case REQ_DUMP_NODES: {
998                                 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);
999                                 if(n != 16) {
1000                                         fprintf(stderr, "Unable to parse node dump from tincd: %s\n", line);
1001                                         return 1;
1002                                 }
1003
1004                                 memcpy(&status, &status_int, sizeof status);
1005
1006                                 if(do_graph) {
1007                                         const char *color = "black";
1008                                         if(!strcmp(host, "MYSELF"))
1009                                                 color = "green";
1010                                         else if(!status.reachable)
1011                                                 color = "red";
1012                                         else if(strcmp(via, node))
1013                                                 color = "orange";
1014                                         else if(!status.validkey)
1015                                                 color = "black";
1016                                         else if(minmtu > 0)
1017                                                 color = "green";
1018                                         printf(" %s [label = \"%s\", color = \"%s\"%s];\n", node, node, color, strcmp(host, "MYSELF") ? "" : ", style = \"filled\"");
1019                                 } else {
1020                                         if(only_reachable && !status.reachable)
1021                                                 continue;
1022                                         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",
1023                                                         node, host, port, cipher, digest, maclength, compression, options, status_int, nexthop, via, distance, pmtu, minmtu, maxmtu);
1024                                 }
1025                         } break;
1026
1027                         case REQ_DUMP_EDGES: {
1028                                 int n = sscanf(line, "%*d %*d %s %s %s port %s %x %d", from, to, host, port, &options, &weight);
1029                                 if(n != 6) {
1030                                         fprintf(stderr, "Unable to parse edge dump from tincd.\n");
1031                                         return 1;
1032                                 }
1033
1034                                 if(do_graph) {
1035                                         float w = 1 + 65536.0 / weight;
1036                                         if(do_graph == 1 && strcmp(node1, node2) > 0)
1037                                                 printf(" %s -- %s [w = %f, weight = %f];\n", node1, node2, w, w);
1038                                         else if(do_graph == 2)
1039                                                 printf(" %s -> %s [w = %f, weight = %f];\n", node1, node2, w, w);
1040                                 } else {
1041                                         printf("%s to %s at %s port %s options %x weight %d\n", from, to, host, port, options, weight);
1042                                 }
1043                         } break;
1044
1045                         case REQ_DUMP_SUBNETS: {
1046                                 int n = sscanf(line, "%*d %*d %s %s", subnet, node);
1047                                 if(n != 2) {
1048                                         fprintf(stderr, "Unable to parse subnet dump from tincd.\n");
1049                                         return 1;
1050                                 }
1051                                 printf("%s owner %s\n", strip_weight(subnet), node);
1052                         } break;
1053
1054                         case REQ_DUMP_CONNECTIONS: {
1055                                 int n = sscanf(line, "%*d %*d %s %s port %s %x %d %x", node, host, port, &options, &socket, &status_int);
1056                                 if(n != 6) {
1057                                         fprintf(stderr, "Unable to parse connection dump from tincd.\n");
1058                                         return 1;
1059                                 }
1060                                 printf("%s at %s port %s options %x socket %d status %x\n", node, host, port, options, socket, status_int);
1061                         } break;
1062
1063                         default:
1064                                 fprintf(stderr, "Unable to parse dump from tincd.\n");
1065                                 return 1;
1066                 }
1067         }
1068
1069         fprintf(stderr, "Error receiving dump.\n");
1070         return 1;
1071 }
1072
1073 static int cmd_purge(int argc, char *argv[]) {
1074         if(argc > 1) {
1075                 fprintf(stderr, "Too many arguments!\n");
1076                 return 1;
1077         }
1078
1079         if(!connect_tincd(true))
1080                 return 1;
1081
1082         sendline(fd, "%d %d", CONTROL, REQ_PURGE);
1083         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
1084                 fprintf(stderr, "Could not purge old information.\n");
1085                 return 1;
1086         }
1087
1088         return 0;
1089 }
1090
1091 static int cmd_debug(int argc, char *argv[]) {
1092         if(argc != 2) {
1093                 fprintf(stderr, "Invalid number of arguments.\n");
1094                 return 1;
1095         }
1096
1097         if(!connect_tincd(true))
1098                 return 1;
1099
1100         int debuglevel = atoi(argv[1]);
1101         int origlevel;
1102
1103         sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
1104         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
1105                 fprintf(stderr, "Could not set debug level.\n");
1106                 return 1;
1107         }
1108
1109         fprintf(stderr, "Old level %d, new level %d.\n", origlevel, debuglevel);
1110         return 0;
1111 }
1112
1113 static int cmd_retry(int argc, char *argv[]) {
1114         if(argc > 1) {
1115                 fprintf(stderr, "Too many arguments!\n");
1116                 return 1;
1117         }
1118
1119         if(!connect_tincd(true))
1120                 return 1;
1121
1122         sendline(fd, "%d %d", CONTROL, REQ_RETRY);
1123         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
1124                 fprintf(stderr, "Could not retry outgoing connections.\n");
1125                 return 1;
1126         }
1127
1128         return 0;
1129 }
1130
1131 static int cmd_connect(int argc, char *argv[]) {
1132         if(argc != 2) {
1133                 fprintf(stderr, "Invalid number of arguments.\n");
1134                 return 1;
1135         }
1136
1137         if(!check_id(argv[1])) {
1138                 fprintf(stderr, "Invalid name for node.\n");
1139                 return 1;
1140         }
1141
1142         if(!connect_tincd(true))
1143                 return 1;
1144
1145         sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, argv[1]);
1146         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
1147                 fprintf(stderr, "Could not connect to %s.\n", argv[1]);
1148                 return 1;
1149         }
1150
1151         return 0;
1152 }
1153
1154 static int cmd_disconnect(int argc, char *argv[]) {
1155         if(argc != 2) {
1156                 fprintf(stderr, "Invalid number of arguments.\n");
1157                 return 1;
1158         }
1159
1160         if(!check_id(argv[1])) {
1161                 fprintf(stderr, "Invalid name for node.\n");
1162                 return 1;
1163         }
1164
1165         if(!connect_tincd(true))
1166                 return 1;
1167
1168         sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, argv[1]);
1169         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
1170                 fprintf(stderr, "Could not disconnect %s.\n", argv[1]);
1171                 return 1;
1172         }
1173
1174         return 0;
1175 }
1176
1177 static int cmd_top(int argc, char *argv[]) {
1178         if(argc > 1) {
1179                 fprintf(stderr, "Too many arguments!\n");
1180                 return 1;
1181         }
1182
1183 #ifdef HAVE_CURSES
1184         if(!connect_tincd(true))
1185                 return 1;
1186
1187         top(fd);
1188         return 0;
1189 #else
1190         fprintf(stderr, "This version of tinc was compiled without support for the curses library.\n");
1191         return 1;
1192 #endif
1193 }
1194
1195 static int cmd_pcap(int argc, char *argv[]) {
1196         if(argc > 2) {
1197                 fprintf(stderr, "Too many arguments!\n");
1198                 return 1;
1199         }
1200
1201         if(!connect_tincd(true))
1202                 return 1;
1203
1204         pcap(fd, stdout, argc > 1 ? atoi(argv[1]) : 0);
1205         return 0;
1206 }
1207
1208 #ifdef SIGINT
1209 static void sigint_handler(int sig) {
1210         fprintf(stderr, "\n");
1211         shutdown(fd, SHUT_RDWR);
1212 }
1213 #endif
1214
1215 static int cmd_log(int argc, char *argv[]) {
1216         if(argc > 2) {
1217                 fprintf(stderr, "Too many arguments!\n");
1218                 return 1;
1219         }
1220
1221         if(!connect_tincd(true))
1222                 return 1;
1223
1224 #ifdef SIGINT
1225         signal(SIGINT, sigint_handler);
1226 #endif
1227
1228         logcontrol(fd, stdout, argc > 1 ? atoi(argv[1]) : -1);
1229
1230 #ifdef SIGINT
1231         signal(SIGINT, SIG_DFL);
1232 #endif
1233
1234         close(fd);
1235         fd = -1;
1236         return 0;
1237 }
1238
1239 static int cmd_pid(int argc, char *argv[]) {
1240         if(argc > 1) {
1241                 fprintf(stderr, "Too many arguments!\n");
1242                 return 1;
1243         }
1244
1245         if(!connect_tincd(true) && !pid)
1246                 return 1;
1247
1248         printf("%d\n", pid);
1249         return 0;
1250 }
1251
1252 int rstrip(char *value) {
1253         int len = strlen(value);
1254         while(len && strchr("\t\r\n ", value[len - 1]))
1255                 value[--len] = 0;
1256         return len;
1257 }
1258
1259 char *get_my_name(bool verbose) {
1260         FILE *f = fopen(tinc_conf, "r");
1261         if(!f) {
1262                 if(verbose)
1263                         fprintf(stderr, "Could not open %s: %s\n", tinc_conf, strerror(errno));
1264                 return NULL;
1265         }
1266
1267         char buf[4096];
1268         char *value;
1269         while(fgets(buf, sizeof buf, f)) {
1270                 int len = strcspn(buf, "\t =");
1271                 value = buf + len;
1272                 value += strspn(value, "\t ");
1273                 if(*value == '=') {
1274                         value++;
1275                         value += strspn(value, "\t ");
1276                 }
1277                 if(!rstrip(value))
1278                         continue;
1279                 buf[len] = 0;
1280                 if(strcasecmp(buf, "Name"))
1281                         continue;
1282                 if(*value) {
1283                         fclose(f);
1284                         return strdup(value);
1285                 }
1286         }
1287
1288         fclose(f);
1289         if(verbose)
1290                 fprintf(stderr, "Could not find Name in %s.\n", tinc_conf);
1291         return NULL;
1292 }
1293
1294 const var_t variables[] = {
1295         /* Server configuration */
1296         {"AddressFamily", VAR_SERVER},
1297         {"AutoConnect", VAR_SERVER | VAR_SAFE},
1298         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
1299         {"BindToInterface", VAR_SERVER},
1300         {"Broadcast", VAR_SERVER | VAR_SAFE},
1301         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
1302         {"DecrementTTL", VAR_SERVER},
1303         {"Device", VAR_SERVER},
1304         {"DeviceType", VAR_SERVER},
1305         {"DirectOnly", VAR_SERVER},
1306         {"Ed25519PrivateKeyFile", VAR_SERVER},
1307         {"ExperimentalProtocol", VAR_SERVER},
1308         {"Forwarding", VAR_SERVER},
1309         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
1310         {"Hostnames", VAR_SERVER},
1311         {"IffOneQueue", VAR_SERVER},
1312         {"Interface", VAR_SERVER},
1313         {"KeyExpire", VAR_SERVER},
1314         {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
1315         {"LocalDiscovery", VAR_SERVER},
1316         {"MACExpire", VAR_SERVER},
1317         {"MaxConnectionBurst", VAR_SERVER},
1318         {"MaxOutputBufferSize", VAR_SERVER},
1319         {"MaxTimeout", VAR_SERVER},
1320         {"Mode", VAR_SERVER | VAR_SAFE},
1321         {"Name", VAR_SERVER},
1322         {"PingInterval", VAR_SERVER},
1323         {"PingTimeout", VAR_SERVER},
1324         {"PriorityInheritance", VAR_SERVER},
1325         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
1326         {"PrivateKeyFile", VAR_SERVER},
1327         {"ProcessPriority", VAR_SERVER},
1328         {"Proxy", VAR_SERVER},
1329         {"ReplayWindow", VAR_SERVER},
1330         {"ScriptsExtension", VAR_SERVER},
1331         {"ScriptsInterpreter", VAR_SERVER},
1332         {"StrictSubnets", VAR_SERVER},
1333         {"TunnelServer", VAR_SERVER},
1334         {"UDPRcvBuf", VAR_SERVER},
1335         {"UDPSndBuf", VAR_SERVER},
1336         {"VDEGroup", VAR_SERVER},
1337         {"VDEPort", VAR_SERVER},
1338         /* Host configuration */
1339         {"Address", VAR_HOST | VAR_MULTIPLE},
1340         {"Cipher", VAR_SERVER | VAR_HOST},
1341         {"ClampMSS", VAR_SERVER | VAR_HOST},
1342         {"Compression", VAR_SERVER | VAR_HOST},
1343         {"Digest", VAR_SERVER | VAR_HOST},
1344         {"Ed25519PublicKey", VAR_HOST},
1345         {"Ed25519PublicKeyFile", VAR_SERVER | VAR_HOST},
1346         {"IndirectData", VAR_SERVER | VAR_HOST},
1347         {"MACLength", VAR_SERVER | VAR_HOST},
1348         {"PMTU", VAR_SERVER | VAR_HOST},
1349         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
1350         {"Port", VAR_HOST},
1351         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
1352         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
1353         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
1354         {"TCPOnly", VAR_SERVER | VAR_HOST},
1355         {"Weight", VAR_HOST | VAR_SAFE},
1356         {NULL, 0}
1357 };
1358
1359 static int cmd_config(int argc, char *argv[]) {
1360         if(argc < 2) {
1361                 fprintf(stderr, "Invalid number of arguments.\n");
1362                 return 1;
1363         }
1364
1365         if(strcasecmp(argv[0], "config"))
1366                 argv--, argc++;
1367
1368         int action = -2;
1369         if(!strcasecmp(argv[1], "get")) {
1370                 argv++, argc--;
1371         } else if(!strcasecmp(argv[1], "add")) {
1372                 argv++, argc--, action = 1;
1373         } else if(!strcasecmp(argv[1], "del")) {
1374                 argv++, argc--, action = -1;
1375         } else if(!strcasecmp(argv[1], "replace") || !strcasecmp(argv[1], "set") || !strcasecmp(argv[1], "change")) {
1376                 argv++, argc--, action = 0;
1377         }
1378
1379         if(argc < 2) {
1380                 fprintf(stderr, "Invalid number of arguments.\n");
1381                 return 1;
1382         }
1383
1384         // Concatenate the rest of the command line
1385         strncpy(line, argv[1], sizeof line - 1);
1386         for(int i = 2; i < argc; i++) {
1387                 strncat(line, " ", sizeof line - 1 - strlen(line));
1388                 strncat(line, argv[i], sizeof line - 1 - strlen(line));
1389         }
1390
1391         // Liberal parsing into node name, variable name and value.
1392         char *node = NULL;
1393         char *variable;
1394         char *value;
1395         int len;
1396
1397         len = strcspn(line, "\t =");
1398         value = line + len;
1399         value += strspn(value, "\t ");
1400         if(*value == '=') {
1401                 value++;
1402                 value += strspn(value, "\t ");
1403         }
1404         line[len] = '\0';
1405         variable = strchr(line, '.');
1406         if(variable) {
1407                 node = line;
1408                 *variable++ = 0;
1409         } else {
1410                 variable = line;
1411         }
1412
1413         if(!*variable) {
1414                 fprintf(stderr, "No variable given.\n");
1415                 return 1;
1416         }
1417
1418         if(action >= 0 && !*value) {
1419                 fprintf(stderr, "No value for variable given.\n");
1420                 return 1;
1421         }
1422
1423         if(action < -1 && *value)
1424                 action = 0;
1425
1426         /* Some simple checks. */
1427         bool found = false;
1428         bool warnonremove = false;
1429
1430         for(int i = 0; variables[i].name; i++) {
1431                 if(strcasecmp(variables[i].name, variable))
1432                         continue;
1433
1434                 found = true;
1435                 variable = (char *)variables[i].name;
1436
1437                 /* Discourage use of obsolete variables. */
1438
1439                 if(variables[i].type & VAR_OBSOLETE && action >= 0) {
1440                         if(force) {
1441                                 fprintf(stderr, "Warning: %s is an obsolete variable!\n", variable);
1442                         } else {
1443                                 fprintf(stderr, "%s is an obsolete variable! Use --force to use it anyway.\n", variable);
1444                                 return 1;
1445                         }
1446                 }
1447
1448                 /* Don't put server variables in host config files */
1449
1450                 if(node && !(variables[i].type & VAR_HOST) && action >= 0) {
1451                         if(force) {
1452                                 fprintf(stderr, "Warning: %s is not a host configuration variable!\n", variable);
1453                         } else {
1454                                 fprintf(stderr, "%s is not a host configuration variable! Use --force to use it anyway.\n", variable);
1455                                 return 1;
1456                         }
1457                 }
1458
1459                 /* Should this go into our own host config file? */
1460
1461                 if(!node && !(variables[i].type & VAR_SERVER)) {
1462                         node = get_my_name(true);
1463                         if(!node)
1464                                 return 1;
1465                 }
1466
1467                 /* Change "add" into "set" for variables that do not allow multiple occurences.
1468                    Turn on warnings when it seems variables might be removed unintentionally. */
1469
1470                 if(action == 1 && !(variables[i].type & VAR_MULTIPLE)) {
1471                         warnonremove = true;
1472                         action = 0;
1473                 } else if(action == 0 && (variables[i].type & VAR_MULTIPLE)) {
1474                         warnonremove = true;
1475                 }
1476
1477                 break;
1478         }
1479
1480         if(node && !check_id(node)) {
1481                 fprintf(stderr, "Invalid name for node.\n");
1482                 return 1;
1483         }
1484
1485         if(!found) {
1486                 if(force || action < 0) {
1487                         fprintf(stderr, "Warning: %s is not a known configuration variable!\n", variable);
1488                 } else {
1489                         fprintf(stderr, "%s: is not a known configuration variable! Use --force to use it anyway.\n", variable);
1490                         return 1;
1491                 }
1492         }
1493
1494         // Open the right configuration file.
1495         char *filename;
1496         if(node)
1497                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, node);
1498         else
1499                 filename = tinc_conf;
1500
1501         FILE *f = fopen(filename, "r");
1502         if(!f) {
1503                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1504                 return 1;
1505         }
1506
1507         char *tmpfile = NULL;
1508         FILE *tf = NULL;
1509
1510         if(action >= -1) {
1511                 xasprintf(&tmpfile, "%s.config.tmp", filename);
1512                 tf = fopen(tmpfile, "w");
1513                 if(!tf) {
1514                         fprintf(stderr, "Could not open temporary file %s: %s\n", tmpfile, strerror(errno));
1515                         fclose(f);
1516                         return 1;
1517                 }
1518         }
1519
1520         // Copy the file, making modifications on the fly, unless we are just getting a value.
1521         char buf1[4096];
1522         char buf2[4096];
1523         bool set = false;
1524         bool removed = false;
1525         found = false;
1526
1527         while(fgets(buf1, sizeof buf1, f)) {
1528                 buf1[sizeof buf1 - 1] = 0;
1529                 strncpy(buf2, buf1, sizeof buf2);
1530
1531                 // Parse line in a simple way
1532                 char *bvalue;
1533                 int len;
1534
1535                 len = strcspn(buf2, "\t =");
1536                 bvalue = buf2 + len;
1537                 bvalue += strspn(bvalue, "\t ");
1538                 if(*bvalue == '=') {
1539                         bvalue++;
1540                         bvalue += strspn(bvalue, "\t ");
1541                 }
1542                 rstrip(bvalue);
1543                 buf2[len] = '\0';
1544
1545                 // Did it match?
1546                 if(!strcasecmp(buf2, variable)) {
1547                         // Get
1548                         if(action < -1) {
1549                                 found = true;
1550                                 printf("%s\n", bvalue);
1551                         // Del
1552                         } else if(action == -1) {
1553                                 if(!*value || !strcasecmp(bvalue, value)) {
1554                                         removed = true;
1555                                         continue;
1556                                 }
1557                         // Set
1558                         } else if(action == 0) {
1559                                 // Warn if "set" was used for variables that can occur multiple times
1560                                 if(warnonremove && strcasecmp(bvalue, value))
1561                                         fprintf(stderr, "Warning: removing %s = %s\n", variable, bvalue);
1562
1563                                 // Already set? Delete the rest...
1564                                 if(set)
1565                                         continue;
1566
1567                                 // Otherwise, replace.
1568                                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1569                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1570                                         return 1;
1571                                 }
1572                                 set = true;
1573                                 continue;
1574                         }
1575                 }
1576
1577                 if(action >= -1) {
1578                         // Copy original line...
1579                         if(fputs(buf1, tf) < 0) {
1580                                 fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1581                                 return 1;
1582                         }
1583
1584                         // Add newline if it is missing...
1585                         if(*buf1 && buf1[strlen(buf1) - 1] != '\n') {
1586                                 if(fputc('\n', tf) < 0) {
1587                                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1588                                         return 1;
1589                                 }
1590                         }
1591                 }
1592         }
1593
1594         // Make sure we read everything...
1595         if(ferror(f) || !feof(f)) {
1596                 fprintf(stderr, "Error while reading from configuration file %s: %s\n", filename, strerror(errno));
1597                 return 1;
1598         }
1599
1600         if(fclose(f)) {
1601                 fprintf(stderr, "Error closing configuration file %s: %s\n", filename, strerror(errno));
1602                 return 1;
1603         }
1604
1605         // Add new variable if necessary.
1606         if(action > 0 || (action == 0 && !set)) {
1607                 if(fprintf(tf, "%s = %s\n", variable, value) < 0) {
1608                         fprintf(stderr, "Error writing to temporary file %s: %s\n", tmpfile, strerror(errno));
1609                         return 1;
1610                 }
1611         }
1612
1613         if(action < -1) {
1614                 if(!found)
1615                         fprintf(stderr, "No matching configuration variables found.\n");
1616                 return 1;
1617         }
1618
1619         // Make sure we wrote everything...
1620         if(fclose(tf)) {
1621                 fprintf(stderr, "Error closing temporary file %s: %s\n", tmpfile, strerror(errno));
1622                 return 1;
1623         }
1624
1625         // Could we find what we had to remove?
1626         if(action < 0 && !removed) {
1627                 remove(tmpfile);
1628                 fprintf(stderr, "No configuration variables deleted.\n");
1629                 return 1;
1630         }
1631
1632         // Replace the configuration file with the new one
1633 #ifdef HAVE_MINGW
1634         if(remove(filename)) {
1635                 fprintf(stderr, "Error replacing file %s: %s\n", filename, strerror(errno));
1636                 return 1;
1637         }
1638 #endif
1639         if(rename(tmpfile, filename)) {
1640                 fprintf(stderr, "Error renaming temporary file %s to configuration file %s: %s\n", tmpfile, filename, strerror(errno));
1641                 return 1;
1642         }
1643
1644         // Silently try notifying a running tincd of changes.
1645         if(connect_tincd(false))
1646                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1647
1648         return 0;
1649 }
1650
1651 bool check_id(const char *name) {
1652         if(!name || !*name)
1653                 return false;
1654
1655         for(int i = 0; i < strlen(name); i++) {
1656                 if(!isalnum(name[i]) && name[i] != '_')
1657                         return false;
1658         }
1659
1660         return true;
1661 }
1662
1663 static bool try_bind(int port) {
1664         struct addrinfo *ai = NULL;
1665         struct addrinfo hint = {
1666                 .ai_flags = AI_PASSIVE,
1667                 .ai_family = AF_UNSPEC,
1668                 .ai_socktype = SOCK_STREAM,
1669                 .ai_protocol = IPPROTO_TCP,
1670         };
1671
1672         char portstr[16];
1673         snprintf(portstr, sizeof portstr, "%d", port);
1674
1675         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
1676                 return false;
1677
1678         while(ai) {
1679                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
1680                 if(!fd)
1681                         return false;
1682                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
1683                 closesocket(fd);
1684                 if(result)
1685                         return false;
1686                 ai = ai->ai_next;
1687         }
1688
1689         return true;
1690 }
1691
1692 int check_port(char *name) {
1693         if(try_bind(655))
1694                 return 655;
1695
1696         fprintf(stderr, "Warning: could not bind to port 655. ");
1697
1698         for(int i = 0; i < 100; i++) {
1699                 int port = 0x1000 + (rand() & 0x7fff);
1700                 if(try_bind(port)) {
1701                         char *filename;
1702                         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
1703                         FILE *f = fopen(filename, "a");
1704                         free(filename);
1705                         if(!f) {
1706                                 fprintf(stderr, "Please change tinc's Port manually.\n");
1707                                 return 0;
1708                         }
1709
1710                         fprintf(f, "Port = %d\n", port);
1711                         fclose(f);
1712                         fprintf(stderr, "Tinc will instead listen on port %d.\n", port);
1713                         return port;
1714                 }
1715         }
1716
1717         fprintf(stderr, "Please change tinc's Port manually.\n");
1718         return 0;
1719 }
1720
1721 static int cmd_init(int argc, char *argv[]) {
1722         if(!access(tinc_conf, F_OK)) {
1723                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1724                 return 1;
1725         }
1726
1727         if(argc > 2) {
1728                 fprintf(stderr, "Too many arguments!\n");
1729                 return 1;
1730         } else if(argc < 2) {
1731                 if(tty) {
1732                         char buf[1024];
1733                         fprintf(stderr, "Enter the Name you want your tinc node to have: ");
1734                         if(!fgets(buf, sizeof buf, stdin)) {
1735                                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1736                                 return 1;
1737                         }
1738                         int len = rstrip(buf);
1739                         if(!len) {
1740                                 fprintf(stderr, "No name given!\n");
1741                                 return 1;
1742                         }
1743                         name = strdup(buf);
1744                 } else {
1745                         fprintf(stderr, "No Name given!\n");
1746                         return 1;
1747                 }
1748         } else {
1749                 name = strdup(argv[1]);
1750                 if(!*name) {
1751                         fprintf(stderr, "No Name given!\n");
1752                         return 1;
1753                 }
1754         }
1755
1756         if(!check_id(name)) {
1757                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
1758                 return 1;
1759         }
1760
1761         if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1762                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1763                 return 1;
1764         }
1765
1766         if(mkdir(confbase, 0777) && errno != EEXIST) {
1767                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1768                 return 1;
1769         }
1770
1771         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
1772                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
1773                 return 1;
1774         }
1775
1776         FILE *f = fopen(tinc_conf, "w");
1777         if(!f) {
1778                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
1779                 return 1;
1780         }
1781
1782         fprintf(f, "Name = %s\n", name);
1783         fclose(f);
1784
1785         if(!rsa_keygen(2048, false) || !ed25519_keygen(false))
1786                 return 1;
1787
1788         check_port(name);
1789
1790 #ifndef HAVE_MINGW
1791         char *filename;
1792         xasprintf(&filename, "%s" SLASH "tinc-up", confbase);
1793         if(access(filename, F_OK)) {
1794                 FILE *f = fopenmask(filename, "w", 0777);
1795                 if(!f) {
1796                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
1797                         return 1;
1798                 }
1799                 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");
1800                 fclose(f);
1801         }
1802 #endif
1803
1804         return 0;
1805
1806 }
1807
1808 static int cmd_generate_keys(int argc, char *argv[]) {
1809         if(argc > 2) {
1810                 fprintf(stderr, "Too many arguments!\n");
1811                 return 1;
1812         }
1813
1814         if(!name)
1815                 name = get_my_name(false);
1816
1817         return !(rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true) && ed25519_keygen(true));
1818 }
1819
1820 static int cmd_generate_rsa_keys(int argc, char *argv[]) {
1821         if(argc > 2) {
1822                 fprintf(stderr, "Too many arguments!\n");
1823                 return 1;
1824         }
1825
1826         if(!name)
1827                 name = get_my_name(false);
1828
1829         return !rsa_keygen(argc > 1 ? atoi(argv[1]) : 2048, true);
1830 }
1831
1832 static int cmd_generate_ed25519_keys(int argc, char *argv[]) {
1833         if(argc > 1) {
1834                 fprintf(stderr, "Too many arguments!\n");
1835                 return 1;
1836         }
1837
1838         if(!name)
1839                 name = get_my_name(false);
1840
1841         return !ed25519_keygen(true);
1842 }
1843
1844 static int cmd_help(int argc, char *argv[]) {
1845         usage(false);
1846         return 0;
1847 }
1848
1849 static int cmd_version(int argc, char *argv[]) {
1850         if(argc > 1) {
1851                 fprintf(stderr, "Too many arguments!\n");
1852                 return 1;
1853         }
1854
1855         version();
1856         return 0;
1857 }
1858
1859 static int cmd_info(int argc, char *argv[]) {
1860         if(argc != 2) {
1861                 fprintf(stderr, "Invalid number of arguments.\n");
1862                 return 1;
1863         }
1864
1865         if(!connect_tincd(true))
1866                 return 1;
1867
1868         return info(fd, argv[1]);
1869 }
1870
1871 static const char *conffiles[] = {
1872         "tinc.conf",
1873         "tinc-up",
1874         "tinc-down",
1875         "subnet-up",
1876         "subnet-down",
1877         "host-up",
1878         "host-down",
1879         NULL,
1880 };
1881
1882 static int cmd_edit(int argc, char *argv[]) {
1883         if(argc != 2) {
1884                 fprintf(stderr, "Invalid number of arguments.\n");
1885                 return 1;
1886         }
1887
1888         char *filename = NULL;
1889
1890         if(strncmp(argv[1], "hosts" SLASH, 6)) {
1891                 for(int i = 0; conffiles[i]; i++) {
1892                         if(!strcmp(argv[1], conffiles[i])) {
1893                                 xasprintf(&filename, "%s" SLASH "%s", confbase, argv[1]);
1894                                 break;
1895                         }
1896                 }
1897         } else {
1898                 argv[1] += 6;
1899         }
1900
1901         if(!filename) {
1902                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, argv[1]);
1903                 char *dash = strchr(argv[1], '-');
1904                 if(dash) {
1905                         *dash++ = 0;
1906                         if((strcmp(dash, "up") && strcmp(dash, "down")) || !check_id(argv[1])) {
1907                                 fprintf(stderr, "Invalid configuration filename.\n");
1908                                 return 1;
1909                         }
1910                 }
1911         }
1912
1913         char *command;
1914 #ifndef HAVE_MINGW
1915         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ?: getenv("EDITOR") ?: "vi", filename);
1916 #else
1917         xasprintf(&command, "edit \"%s\"", filename);
1918 #endif
1919         int result = system(command);
1920         if(result)
1921                 return result;
1922
1923         // Silently try notifying a running tincd of changes.
1924         if(connect_tincd(false))
1925                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
1926
1927         return 0;
1928 }
1929
1930 static int export(const char *name, FILE *out) {
1931         char *filename;
1932         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
1933         FILE *in = fopen(filename, "r");
1934         if(!in) {
1935                 fprintf(stderr, "Could not open configuration file %s: %s\n", filename, strerror(errno));
1936                 return 1;
1937         }
1938
1939         fprintf(out, "Name = %s\n", name);
1940         char buf[4096];
1941         while(fgets(buf, sizeof buf, in)) {
1942                 if(strcspn(buf, "\t =") != 4 || strncasecmp(buf, "Name", 4))
1943                         fputs(buf, out);
1944         }
1945
1946         if(ferror(in)) {
1947                 fprintf(stderr, "Error while reading configuration file %s: %s\n", filename, strerror(errno));
1948                 fclose(in);
1949                 return 1;
1950         }
1951
1952         fclose(in);
1953         return 0;
1954 }
1955
1956 static int cmd_export(int argc, char *argv[]) {
1957         if(argc > 1) {
1958                 fprintf(stderr, "Too many arguments!\n");
1959                 return 1;
1960         }
1961
1962         char *name = get_my_name(true);
1963         if(!name)
1964                 return 1;
1965
1966         int result = export(name, stdout);
1967         if(!tty)
1968                 fclose(stdout);
1969
1970         free(name);
1971         return result;
1972 }
1973
1974 static int cmd_export_all(int argc, char *argv[]) {
1975         if(argc > 1) {
1976                 fprintf(stderr, "Too many arguments!\n");
1977                 return 1;
1978         }
1979
1980         DIR *dir = opendir(hosts_dir);
1981         if(!dir) {
1982                 fprintf(stderr, "Could not open host configuration directory %s: %s\n", hosts_dir, strerror(errno));
1983                 return 1;
1984         }
1985
1986         bool first = true;
1987         int result = 0;
1988         struct dirent *ent;
1989
1990         while((ent = readdir(dir))) {
1991                 if(!check_id(ent->d_name))
1992                         continue;
1993
1994                 if(first)
1995                         first = false;
1996                 else
1997                         printf("#---------------------------------------------------------------#\n");
1998
1999                 result |= export(ent->d_name, stdout);
2000         }
2001
2002         closedir(dir);
2003         if(!tty)
2004                 fclose(stdout);
2005         return result;
2006 }
2007
2008 static int cmd_import(int argc, char *argv[]) {
2009         if(argc > 1) {
2010                 fprintf(stderr, "Too many arguments!\n");
2011                 return 1;
2012         }
2013
2014         FILE *in = stdin;
2015         FILE *out = NULL;
2016
2017         char buf[4096];
2018         char name[4096];
2019         char *filename = NULL;
2020         int count = 0;
2021         bool firstline = true;
2022
2023         while(fgets(buf, sizeof buf, in)) {
2024                 if(sscanf(buf, "Name = %s", name) == 1) {
2025                         firstline = false;
2026
2027                         if(!check_id(name)) {
2028                                 fprintf(stderr, "Invalid Name in input!\n");
2029                                 return 1;
2030                         }
2031
2032                         if(out)
2033                                 fclose(out);
2034
2035                         free(filename);
2036                         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
2037
2038                         if(!force && !access(filename, F_OK)) {
2039                                 fprintf(stderr, "Host configuration file %s already exists, skipping.\n", filename);
2040                                 out = NULL;
2041                                 continue;
2042                         }
2043
2044                         out = fopen(filename, "w");
2045                         if(!out) {
2046                                 fprintf(stderr, "Error creating configuration file %s: %s\n", filename, strerror(errno));
2047                                 return 1;
2048                         }
2049
2050                         count++;
2051                         continue;
2052                 } else if(firstline) {
2053                         fprintf(stderr, "Junk at the beginning of the input, ignoring.\n");
2054                         firstline = false;
2055                 }
2056
2057
2058                 if(!strcmp(buf, "#---------------------------------------------------------------#\n"))
2059                         continue;
2060
2061                 if(out) {
2062                         if(fputs(buf, out) < 0) {
2063                                 fprintf(stderr, "Error writing to host configuration file %s: %s\n", filename, strerror(errno));
2064                                 return 1;
2065                         }
2066                 }
2067         }
2068
2069         if(out)
2070                 fclose(out);
2071
2072         if(count) {
2073                 fprintf(stderr, "Imported %d host configuration files.\n", count);
2074                 return 0;
2075         } else {
2076                 fprintf(stderr, "No host configuration files imported.\n");
2077                 return 1;
2078         }
2079 }
2080
2081 static int cmd_exchange(int argc, char *argv[]) {
2082         return cmd_export(argc, argv) ?: cmd_import(argc, argv);
2083 }
2084
2085 static int cmd_exchange_all(int argc, char *argv[]) {
2086         return cmd_export_all(argc, argv) ?: cmd_import(argc, argv);
2087 }
2088
2089 static int switch_network(char *name) {
2090         if(fd >= 0) {
2091                 close(fd);
2092                 fd = -1;
2093         }
2094
2095         free(confbase);
2096         confbase = NULL;
2097         free(pidfilename);
2098         pidfilename = NULL;
2099         free(logfilename);
2100         logfilename = NULL;
2101         free(unixsocketname);
2102         unixsocketname = NULL;
2103         free(tinc_conf);
2104         free(hosts_dir);
2105         free(prompt);
2106
2107         free(netname);
2108         netname = strcmp(name, ".") ? xstrdup(name) : NULL;
2109
2110         make_names();
2111         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2112         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2113         xasprintf(&prompt, "%s> ", identname);
2114
2115         return 0;
2116 }
2117
2118 static int cmd_network(int argc, char *argv[]) {
2119         if(argc > 2) {
2120                 fprintf(stderr, "Too many arguments!\n");
2121                 return 1;
2122         }
2123
2124         if(argc == 2)
2125                 return switch_network(argv[1]);
2126
2127         DIR *dir = opendir(confdir);
2128         if(!dir) {
2129                 fprintf(stderr, "Could not read directory %s: %s\n", confdir, strerror(errno));
2130                 return 1;
2131         }
2132
2133         struct dirent *ent;
2134         while((ent = readdir(dir))) {
2135                 if(*ent->d_name == '.')
2136                         continue;
2137
2138                 if(!strcmp(ent->d_name, "tinc.conf")) {
2139                         printf(".\n");
2140                         continue;
2141                 }
2142
2143                 char *fname;
2144                 xasprintf(&fname, "%s/%s/tinc.conf", confdir, ent->d_name);
2145                 if(!access(fname, R_OK))
2146                         printf("%s\n", ent->d_name);
2147                 free(fname);
2148         }
2149
2150         closedir(dir);
2151
2152         return 0;
2153 }
2154
2155 static const struct {
2156         const char *command;
2157         int (*function)(int argc, char *argv[]);
2158         bool hidden;
2159 } commands[] = {
2160         {"start", cmd_start},
2161         {"stop", cmd_stop},
2162         {"restart", cmd_restart},
2163         {"reload", cmd_reload},
2164         {"dump", cmd_dump},
2165         {"purge", cmd_purge},
2166         {"debug", cmd_debug},
2167         {"retry", cmd_retry},
2168         {"connect", cmd_connect},
2169         {"disconnect", cmd_disconnect},
2170         {"top", cmd_top},
2171         {"pcap", cmd_pcap},
2172         {"log", cmd_log},
2173         {"pid", cmd_pid},
2174         {"config", cmd_config, true},
2175         {"add", cmd_config},
2176         {"del", cmd_config},
2177         {"get", cmd_config},
2178         {"set", cmd_config},
2179         {"init", cmd_init},
2180         {"generate-keys", cmd_generate_keys},
2181         {"generate-rsa-keys", cmd_generate_rsa_keys},
2182         {"generate-ed25519-keys", cmd_generate_ed25519_keys},
2183         {"help", cmd_help},
2184         {"version", cmd_version},
2185         {"info", cmd_info},
2186         {"edit", cmd_edit},
2187         {"export", cmd_export},
2188         {"export-all", cmd_export_all},
2189         {"import", cmd_import},
2190         {"exchange", cmd_exchange},
2191         {"exchange-all", cmd_exchange_all},
2192         {"invite", cmd_invite},
2193         {"join", cmd_join},
2194         {"network", cmd_network},
2195         {NULL, NULL},
2196 };
2197
2198 #ifdef HAVE_READLINE
2199 static char *complete_command(const char *text, int state) {
2200         static int i;
2201
2202         if(!state)
2203                 i = 0;
2204         else
2205                 i++;
2206
2207         while(commands[i].command) {
2208                 if(!commands[i].hidden && !strncasecmp(commands[i].command, text, strlen(text)))
2209                         return xstrdup(commands[i].command);
2210                 i++;
2211         }
2212
2213         return NULL;
2214 }
2215
2216 static char *complete_dump(const char *text, int state) {
2217         const char *matches[] = {"reachable", "nodes", "edges", "subnets", "connections", "graph", NULL};
2218         static int i;
2219
2220         if(!state)
2221                 i = 0;
2222         else
2223                 i++;
2224
2225         while(matches[i]) {
2226                 if(!strncasecmp(matches[i], text, strlen(text)))
2227                         return xstrdup(matches[i]);
2228                 i++;
2229         }
2230
2231         return NULL;
2232 }
2233
2234 static char *complete_config(const char *text, int state) {
2235         static int i;
2236
2237         if(!state)
2238                 i = 0;
2239         else
2240                 i++;
2241
2242         while(variables[i].name) {
2243                 char *dot = strchr(text, '.');
2244                 if(dot) {
2245                         if((variables[i].type & VAR_HOST) && !strncasecmp(variables[i].name, dot + 1, strlen(dot + 1))) {
2246                                 char *match;
2247                                 xasprintf(&match, "%.*s.%s", (int)(dot - text), text, variables[i].name);
2248                                 return match;
2249                         }
2250                 } else {
2251                         if(!strncasecmp(variables[i].name, text, strlen(text)))
2252                                 return xstrdup(variables[i].name);
2253                 }
2254                 i++;
2255         }
2256
2257         return NULL;
2258 }
2259
2260 static char *complete_info(const char *text, int state) {
2261         static int i;
2262         if(!state) {
2263                 i = 0;
2264                 if(!connect_tincd(false))
2265                         return NULL;
2266                 // Check the list of nodes
2267                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
2268                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
2269         }
2270
2271         while(recvline(fd, line, sizeof line)) {
2272                 char item[4096];
2273                 int n = sscanf(line, "%d %d %s", &code, &req, item);
2274                 if(n == 2) {
2275                         i++;
2276                         if(i >= 2)
2277                                 break;
2278                         else
2279                                 continue;
2280                 }
2281
2282                 if(n != 3) {
2283                         fprintf(stderr, "Unable to parse dump from tincd, n = %d, i = %d.\n", n, i);
2284                         break;
2285                 }
2286
2287                 if(!strncmp(item, text, strlen(text)))
2288                         return xstrdup(strip_weight(item));
2289         }
2290
2291         return NULL;
2292 }
2293
2294 static char *complete_nothing(const char *text, int state) {
2295         return NULL;
2296 }
2297
2298 static char **completion (const char *text, int start, int end) {
2299         char **matches = NULL;
2300
2301         if(!start)
2302                 matches = rl_completion_matches(text, complete_command);
2303         else if(!strncasecmp(rl_line_buffer, "dump ", 5))
2304                 matches = rl_completion_matches(text, complete_dump);
2305         else if(!strncasecmp(rl_line_buffer, "add ", 4))
2306                 matches = rl_completion_matches(text, complete_config);
2307         else if(!strncasecmp(rl_line_buffer, "del ", 4))
2308                 matches = rl_completion_matches(text, complete_config);
2309         else if(!strncasecmp(rl_line_buffer, "get ", 4))
2310                 matches = rl_completion_matches(text, complete_config);
2311         else if(!strncasecmp(rl_line_buffer, "set ", 4))
2312                 matches = rl_completion_matches(text, complete_config);
2313         else if(!strncasecmp(rl_line_buffer, "info ", 5))
2314                 matches = rl_completion_matches(text, complete_info);
2315
2316         return matches;
2317 }
2318 #endif
2319
2320 static int cmd_shell(int argc, char *argv[]) {
2321         xasprintf(&prompt, "%s> ", identname);
2322         int result = 0;
2323         char buf[4096];
2324         char *line = NULL;
2325         int maxargs = argc + 16;
2326         char **nargv = xmalloc(maxargs * sizeof *nargv);
2327
2328         for(int i = 0; i < argc; i++)
2329                 nargv[i] = argv[i];
2330
2331 #ifdef HAVE_READLINE
2332         rl_readline_name = "tinc";
2333         rl_completion_entry_function = complete_nothing;
2334         rl_attempted_completion_function = completion;
2335         rl_filename_completion_desired = 0;
2336         char *copy = NULL;
2337 #endif
2338
2339         while(true) {
2340 #ifdef HAVE_READLINE
2341                 if(tty) {
2342                         free(copy);
2343                         free(line);
2344                         rl_basic_word_break_characters = "\t\n ";
2345                         line = readline(prompt);
2346                         if(line)
2347                                 copy = xstrdup(line);
2348                 } else {
2349                         line = fgets(buf, sizeof buf, stdin);
2350                 }
2351 #else
2352                 if(tty)
2353                         fputs(prompt, stdout);
2354
2355                 line = fgets(buf, sizeof buf, stdin);
2356 #endif
2357
2358                 if(!line)
2359                         break;
2360
2361                 /* Ignore comments */
2362
2363                 if(*line == '#')
2364                         continue;
2365
2366                 /* Split */
2367
2368                 int nargc = argc;
2369                 char *p = line + strspn(line, " \t\n");
2370                 char *next = strtok(p, " \t\n");
2371
2372                 while(p && *p) {
2373                         if(nargc >= maxargs) {
2374                                 fprintf(stderr, "next %p '%s', p %p '%s'\n", next, next, p, p);
2375                                 abort();
2376                                 maxargs *= 2;
2377                                 nargv = xrealloc(nargv, maxargs * sizeof *nargv);
2378                         }
2379
2380                         nargv[nargc++] = p;
2381                         p = next;
2382                         next = strtok(NULL, " \t\n");
2383                 }
2384
2385                 if(nargc == argc)
2386                         continue;
2387
2388                 if(!strcasecmp(nargv[argc], "exit") || !strcasecmp(nargv[argc], "quit"))
2389                         return result;
2390
2391                 bool found = false;
2392
2393                 for(int i = 0; commands[i].command; i++) {
2394                         if(!strcasecmp(nargv[argc], commands[i].command)) {
2395                                 result |= commands[i].function(nargc - argc - 1, nargv + argc + 1);
2396                                 found = true;
2397                                 break;
2398                         }
2399                 }
2400
2401 #ifdef HAVE_READLINE
2402                 if(tty && found)
2403                         add_history(copy);
2404 #endif
2405
2406                 if(!found) {
2407                         fprintf(stderr, "Unknown command `%s'.\n", nargv[argc]);
2408                         result |= 1;
2409                 }
2410         }
2411
2412         free(nargv);
2413
2414         if(tty)
2415                 printf("\n");
2416         return result;
2417 }
2418
2419
2420 int main(int argc, char *argv[]) {
2421         program_name = argv[0];
2422         orig_argv = argv;
2423         orig_argc = argc;
2424
2425         if(!parse_options(argc, argv))
2426                 return 1;
2427
2428         make_names();
2429         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
2430         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
2431
2432         if(show_version) {
2433                 version();
2434                 return 0;
2435         }
2436
2437         if(show_help) {
2438                 usage(false);
2439                 return 0;
2440         }
2441
2442 #ifdef HAVE_MINGW
2443         static struct WSAData wsa_state;
2444
2445         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
2446                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
2447                 return false;
2448         }
2449 #endif
2450
2451         srand(time(NULL));
2452         crypto_init();
2453
2454         tty = isatty(0) && isatty(1);
2455
2456         if(optind >= argc)
2457                 return cmd_shell(argc, argv);
2458
2459         for(int i = 0; commands[i].command; i++) {
2460                 if(!strcasecmp(argv[optind], commands[i].command))
2461                         return commands[i].function(argc - optind, argv + optind);
2462         }
2463
2464         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
2465         usage(true);
2466         return 1;
2467 }