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