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