"tincctl init" creates initial directory structure, tinc.conf and keypairs.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2012 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <getopt.h>
23
24 #include "xalloc.h"
25 #include "protocol.h"
26 #include "control_common.h"
27 #include "ecdsagen.h"
28 #include "rsagen.h"
29 #include "utils.h"
30 #include "tincctl.h"
31 #include "top.h"
32
33 /* The name this program was run with. */
34 static char *program_name = NULL;
35
36 /* If nonzero, display usage information and exit. */
37 static bool show_help = false;
38
39 /* If nonzero, print the version on standard output and exit.  */
40 static bool show_version = false;
41
42 static char *name = NULL;
43 static char *identname = NULL;                          /* program name for syslog */
44 static char *pidfilename = NULL;                        /* pid file location */
45 static char controlcookie[1024];
46 char *netname = NULL;
47 char *confbase = NULL;
48
49 #ifdef HAVE_MINGW
50 static struct WSAData wsa_state;
51 #endif
52
53 static struct option const long_options[] = {
54         {"config", required_argument, NULL, 'c'},
55         {"net", required_argument, NULL, 'n'},
56         {"help", no_argument, NULL, 1},
57         {"version", no_argument, NULL, 2},
58         {"pidfile", required_argument, NULL, 5},
59         {NULL, 0, NULL, 0}
60 };
61
62 static void usage(bool status) {
63         if(status)
64                 fprintf(stderr, "Try `%s --help\' for more information.\n",
65                                 program_name);
66         else {
67                 printf("Usage: %s [options] command\n\n", program_name);
68                 printf("Valid options are:\n"
69                                 "  -c, --config=DIR        Read configuration options from DIR.\n"
70                                 "  -n, --net=NETNAME       Connect to net NETNAME.\n"
71                                 "      --pidfile=FILENAME  Read control cookie from FILENAME.\n"
72                                 "      --help              Display this help and exit.\n"
73                                 "      --version           Output version information and exit.\n"
74                                 "\n"
75                                 "Valid commands are:\n"
76                                 "  init [name]                Create initial configuration files.\n"
77                                 "  start                      Start tincd.\n"
78                                 "  stop                       Stop tincd.\n"
79                                 "  restart                    Restart tincd.\n"
80                                 "  reload                     Partially reload configuration of running tincd.\n"
81                                 "  pid                        Show PID of currently running tincd.\n"
82                                 "  generate-keys [bits]       Generate new RSA and ECDSA public/private keypairs.\n"
83                                 "  generate-rsa-keys [bits]   Generate a new RSA public/private keypair.\n"
84                                 "  generate-ecdsa-keys        Generate a new ECDSA public/private keypair.\n"
85                                 "  dump                       Dump a list of one of the following things:\n"
86                                 "    nodes                    - all known nodes in the VPN\n"
87                                 "    edges                    - all known connections in the VPN\n"
88                                 "    subnets                  - all known subnets in the VPN\n"
89                                 "    connections              - all meta connections with ourself\n"
90                                 "    graph                    - graph of the VPN in dotty format\n"
91                                 "  purge                      Purge unreachable nodes\n"
92                                 "  debug N                    Set debug level\n"
93                                 "  retry                      Retry all outgoing connections\n"
94                                 "  disconnect NODE            Close meta connection with NODE\n"
95 #ifdef HAVE_CURSES
96                                 "  top                        Show real-time statistics\n"
97 #endif
98                                 "  pcap [snaplen]             Dump traffic in pcap format [up to snaplen bytes per packet]\n"
99                                 "  log [level]                Dump log output [up to the specified level]\n"
100                                 "\n");
101                 printf("Report bugs to tinc@tinc-vpn.org.\n");
102         }
103 }
104
105 static bool parse_options(int argc, char **argv) {
106         int r;
107         int option_index = 0;
108
109         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
110                 switch (r) {
111                         case 0:                         /* long option */
112                                 break;
113
114                         case 'c':                               /* config file */
115                                 confbase = xstrdup(optarg);
116                                 break;
117
118                         case 'n':                               /* net name given */
119                                 netname = xstrdup(optarg);
120                                 break;
121
122                         case 1:                                 /* show help */
123                                 show_help = true;
124                                 break;
125
126                         case 2:                                 /* show version */
127                                 show_version = true;
128                                 break;
129
130                         case 5:                                 /* open control socket here */
131                                 pidfilename = xstrdup(optarg);
132                                 break;
133
134                         case '?':
135                                 usage(true);
136                                 return false;
137
138                         default:
139                                 break;
140                 }
141         }
142
143         if(!netname) {
144                 netname = getenv("NETNAME");
145                 if(netname)
146                         netname = xstrdup(netname);
147         }
148
149         return true;
150 }
151
152 static FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
153         FILE *r;
154         char *directory;
155         char buf[PATH_MAX];
156         char buf2[PATH_MAX];
157
158         /* Check stdin and stdout */
159         if(isatty(0) && isatty(1)) {
160                 /* Ask for a file and/or directory name. */
161                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
162                                 what, filename);
163                 fflush(stdout);
164
165                 if(fgets(buf, sizeof buf, stdin) == NULL) {
166                         fprintf(stderr, "Error while reading stdin: %s\n",
167                                         strerror(errno));
168                         return NULL;
169                 }
170
171                 size_t len = strlen(buf);
172                 if(len)
173                         buf[--len] = 0;
174
175                 if(len)
176                         filename = buf;
177         }
178
179 #ifdef HAVE_MINGW
180         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
181 #else
182         if(filename[0] != '/') {
183 #endif
184                 /* The directory is a relative path or a filename. */
185                 directory = get_current_dir_name();
186                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
187                 filename = buf2;
188         }
189
190         umask(0077);                            /* Disallow everything for group and other */
191
192         /* Open it first to keep the inode busy */
193
194         r = fopen(filename, mode);
195
196         if(!r) {
197                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
198                 return NULL;
199         }
200
201         return r;
202 }
203
204 /*
205   Generate a public/private ECDSA keypair, and ask for a file to store
206   them in.
207 */
208 static bool ecdsa_keygen() {
209         ecdsa_t key;
210         FILE *f;
211         char *filename;
212
213         fprintf(stderr, "Generating ECDSA keypair:\n");
214
215         if(!ecdsa_generate(&key)) {
216                 fprintf(stderr, "Error during key generation!\n");
217                 return false;
218         } else
219                 fprintf(stderr, "Done.\n");
220
221         xasprintf(&filename, "%s/ecdsa_key.priv", confbase);
222         f = ask_and_open(filename, "private ECDSA key", "a");
223
224         if(!f)
225                 return false;
226   
227 #ifdef HAVE_FCHMOD
228         /* Make it unreadable for others. */
229         fchmod(fileno(f), 0600);
230 #endif
231                 
232         if(ftell(f))
233                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
234
235         ecdsa_write_pem_private_key(&key, f);
236
237         fclose(f);
238         free(filename);
239
240         if(name)
241                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
242         else
243                 xasprintf(&filename, "%s/ecdsa_key.pub", confbase);
244
245         f = ask_and_open(filename, "public ECDSA key", "a");
246
247         if(!f)
248                 return false;
249
250         if(ftell(f))
251                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
252
253         char *pubkey = ecdsa_get_base64_public_key(&key);
254         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
255         free(pubkey);
256
257         fclose(f);
258         free(filename);
259
260         return true;
261 }
262
263 /*
264   Generate a public/private RSA keypair, and ask for a file to store
265   them in.
266 */
267 static bool rsa_keygen(int bits) {
268         rsa_t key;
269         FILE *f;
270         char *filename;
271
272         fprintf(stderr, "Generating %d bits keys:\n", bits);
273
274         if(!rsa_generate(&key, bits, 0x10001)) {
275                 fprintf(stderr, "Error during key generation!\n");
276                 return false;
277         } else
278                 fprintf(stderr, "Done.\n");
279
280         xasprintf(&filename, "%s/rsa_key.priv", confbase);
281         f = ask_and_open(filename, "private RSA key", "a");
282
283         if(!f)
284                 return false;
285   
286 #ifdef HAVE_FCHMOD
287         /* Make it unreadable for others. */
288         fchmod(fileno(f), 0600);
289 #endif
290                 
291         if(ftell(f))
292                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
293
294         rsa_write_pem_private_key(&key, f);
295
296         fclose(f);
297         free(filename);
298
299         if(name)
300                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
301         else
302                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
303
304         f = ask_and_open(filename, "public RSA key", "a");
305
306         if(!f)
307                 return false;
308
309         if(ftell(f))
310                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
311
312         rsa_write_pem_public_key(&key, f);
313
314         fclose(f);
315         free(filename);
316
317         return true;
318 }
319
320 /*
321   Set all files and paths according to netname
322 */
323 static void make_names(void) {
324 #ifdef HAVE_MINGW
325         HKEY key;
326         char installdir[1024] = "";
327         long len = sizeof installdir;
328 #endif
329
330         if(netname)
331                 xasprintf(&identname, "tinc.%s", netname);
332         else
333                 identname = xstrdup("tinc");
334
335 #ifdef HAVE_MINGW
336         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
337                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
338                         if(!confbase) {
339                                 if(netname)
340                                         xasprintf(&confbase, "%s/%s", installdir, netname);
341                                 else
342                                         xasprintf(&confbase, "%s", installdir);
343                         }
344                 }
345                 if(!pidfilename)
346                         xasprintf(&pidfilename, "%s/pid", confbase);
347                 RegCloseKey(key);
348                 if(*installdir)
349                         return;
350         }
351 #endif
352
353         if(!pidfilename)
354                 xasprintf(&pidfilename, "%s/run/%s.pid", LOCALSTATEDIR, identname);
355
356         if(netname) {
357                 if(!confbase)
358                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
359                 else
360                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
361         } else {
362                 if(!confbase)
363                         xasprintf(&confbase, CONFDIR "/tinc");
364         }
365 }
366
367 static char buffer[4096];
368 static size_t blen = 0;
369
370 bool recvline(int fd, char *line, size_t len) {
371         char *newline = NULL;
372
373         while(!(newline = memchr(buffer, '\n', blen))) {
374                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
375                 if(result == -1 && errno == EINTR)
376                         continue;
377                 else if(result <= 0)
378                         return false;
379                 blen += result;
380         }
381
382         if(newline - buffer >= len)
383                 return false;
384
385         len = newline - buffer;
386
387         memcpy(line, buffer, len);
388         line[len] = 0;
389         memmove(buffer, newline + 1, blen - len - 1);
390         blen -= len + 1;
391
392         return true;
393 }
394
395 static bool recvdata(int fd, char *data, size_t len) {
396         while(blen < len) {
397                 int result = recv(fd, buffer + blen, sizeof buffer - blen, 0);
398                 if(result == -1 && errno == EINTR)
399                         continue;
400                 else if(result <= 0)
401                         return false;
402                 blen += result;
403         }
404
405         memcpy(data, buffer, len);
406         memmove(buffer, buffer + len, blen - len);
407         blen -= len;
408
409         return true;
410 }
411
412 bool sendline(int fd, char *format, ...) {
413         static char buffer[4096];
414         char *p = buffer;
415         int blen = 0;
416         va_list ap;
417
418         va_start(ap, format);
419         blen = vsnprintf(buffer, sizeof buffer, format, ap);
420         va_end(ap);
421
422         if(blen < 1 || blen >= sizeof buffer)
423                 return false;
424
425         buffer[blen] = '\n';
426         blen++;
427
428         while(blen) {
429                 int result = send(fd, p, blen, 0);
430                 if(result == -1 && errno == EINTR)
431                         continue;
432                 else if(result <= 0)
433                         return false;
434                 p += result;
435                 blen -= result;
436         }
437
438         return true;    
439 }
440
441 static void pcap(int fd, FILE *out, int snaplen) {
442         sendline(fd, "%d %d %d", CONTROL, REQ_PCAP, snaplen);
443         char data[9018];
444
445         struct {
446                 uint32_t magic;
447                 uint16_t major;
448                 uint16_t minor;
449                 uint32_t tz_offset;
450                 uint32_t tz_accuracy;
451                 uint32_t snaplen;
452                 uint32_t ll_type;
453         } header = {
454                 0xa1b2c3d4,
455                 2, 4,
456                 0, 0,
457                 snaplen ?: sizeof data,
458                 1,
459         };
460
461         struct {
462                 uint32_t tv_sec;
463                 uint32_t tv_usec;
464                 uint32_t len;
465                 uint32_t origlen;
466         } packet;
467
468         struct timeval tv;
469
470         fwrite(&header, sizeof header, 1, out);
471         fflush(out);
472
473         char line[32];
474         while(recvline(fd, line, sizeof line)) {
475                 int code, req, len;
476                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
477                 gettimeofday(&tv, NULL);
478                 if(n != 3 || code != CONTROL || req != REQ_PCAP || len < 0 || len > sizeof data)
479                         break;
480                 if(!recvdata(fd, data, len))
481                         break;
482                 packet.tv_sec = tv.tv_sec;
483                 packet.tv_usec = tv.tv_usec;
484                 packet.len = len;
485                 packet.origlen = len;
486                 fwrite(&packet, sizeof packet, 1, out);
487                 fwrite(data, len, 1, out);
488                 fflush(out);
489         }
490 }
491
492 static void logcontrol(int fd, FILE *out, int level) {
493         sendline(fd, "%d %d %d", CONTROL, REQ_LOG, level);
494         char data[1024];
495         char line[32];
496
497         while(recvline(fd, line, sizeof line)) {
498                 int code, req, len;
499                 int n = sscanf(line, "%d %d %d", &code, &req, &len);
500                 if(n != 3 || code != CONTROL || req != REQ_LOG || len < 0 || len > sizeof data)
501                         break;
502                 if(!recvdata(fd, data, len))
503                         break;
504                 fwrite(data, len, 1, out);
505                 fputc('\n', out);
506                 fflush(out);
507         }
508 }
509
510 #ifdef HAVE_MINGW
511 static bool remove_service(void) {
512         SC_HANDLE manager = NULL;
513         SC_HANDLE service = NULL;
514         SERVICE_STATUS status = {0};
515
516         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
517         if(!manager) {
518                 fprintf(stderr, "Could not open service manager: %s\n", winerror(GetLastError()));
519                 return false;
520         }
521
522         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
523
524         if(!service) {
525                 fprintf(stderr, "Could not open %s service: %s\n", identname, winerror(GetLastError()));
526                 return false;
527         }
528
529         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
530                 fprintf(stderr, "Could not stop %s service: %s\n", identname, winerror(GetLastError()));
531         else
532                 fprintf(stderr, "%s service stopped\n", identname);
533
534         if(!DeleteService(service)) {
535                 fprintf(stderr, "Could not remove %s service: %s\n", identname, winerror(GetLastError()));
536                 return false;
537         }
538
539         fprintf(stderr, "%s service removed\n", identname);
540
541         return true;
542 }
543 #endif
544
545 int main(int argc, char *argv[]) {
546         int fd;
547         int result;
548         char host[128];
549         char port[128];
550         int pid;
551
552         program_name = argv[0];
553
554         if(!parse_options(argc, argv))
555                 return 1;
556         
557         make_names();
558
559         if(show_version) {
560                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
561                            VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
562                 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
563                                 "See the AUTHORS file for a complete list.\n\n"
564                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
565                                 "and you are welcome to redistribute it under certain conditions;\n"
566                                 "see the file COPYING for details.\n");
567
568                 return 0;
569         }
570
571         if(show_help) {
572                 usage(false);
573                 return 0;
574         }
575
576         if(optind >= argc) {
577                 fprintf(stderr, "Not enough arguments.\n");
578                 usage(true);
579                 return 1;
580         }
581
582         // First handle commands that don't involve connecting to a running tinc daemon.
583
584         if(!strcasecmp(argv[optind], "generate-rsa-keys")) {
585                 return !rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048);
586         }
587
588         if(!strcasecmp(argv[optind], "generate-ecdsa-keys")) {
589                 return !ecdsa_keygen();
590         }
591
592         if(!strcasecmp(argv[optind], "generate-keys")) {
593                 return !(rsa_keygen(optind < argc - 1 ? atoi(argv[optind + 1]) : 2048) && ecdsa_keygen());
594         }
595
596         if(!strcasecmp(argv[optind], "start")) {
597                 int i, j;
598                 char *c;
599                 char *slash = strrchr(argv[0], '/');
600 #ifdef HAVE_MINGW
601                 if ((c = strrchr(argv[0], '\\')) > slash)
602                         slash = c;
603 #endif
604                 if (slash++) {
605                         c = xmalloc((slash - argv[0]) + sizeof("tincd"));
606                         sprintf(c, "%.*stincd", (int)(slash - argv[0]), argv[0]);
607                 }
608                 else
609                         c = "tincd";
610                 argv[0] = c;
611                 for(i = j = 1; argv[i]; ++i)
612                         if (i != optind && strcmp(argv[i], "--") != 0)
613                                 argv[j++] = argv[i];
614                 argv[j] = NULL;
615                 execvp(c, argv);
616                 fprintf(stderr, "Could not start %s: %s\n", c, strerror(errno));
617                 return 1;
618         }
619
620         if(!strcasecmp(argv[optind], "init")) {
621                 char *filename = NULL;
622                 xasprintf(&filename, "%s/tinc.conf", confbase);
623                 if(!access(confbase, F_OK)) {
624                         fprintf(stderr, "Configuration file %s already exists!\n", filename);
625                         return 1;
626                 }
627
628                 if(optind >= argc - 1) {
629                         if(isatty(0) && isatty(1)) {
630                                 char buf[1024];
631                                 fprintf(stdout, "Enter the Name you want your tinc node to have: ");
632                                 fflush(stdout);
633                                 if(!fgets(buf, sizeof buf, stdin)) {
634                                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
635                                         return 1;
636                                 }
637                                 int len = strlen(buf);
638                                 if(len)
639                                         buf[--len] = 0;
640                                 if(!len) {
641                                         fprintf(stderr, "No name given!\n");
642                                         return 1;
643                                 }
644                                 name = strdup(buf);
645                         } else {
646                                 fprintf(stderr, "No Name given!\n");
647                                 return 1;
648                         }
649                 } else {
650                         name = strdup(argv[optind + 1]);
651                         if(!*name) {
652                                 fprintf(stderr, "No Name given!\n");
653                                 return 1;
654                         }
655                 }
656
657                 for(int i = 0; i < strlen(name); i++) {
658                         if(!isalnum(name[i]) && name[i] != '_') {
659                                 fprintf(stderr, "Invalid Name! Only a-z, A-Z, 0-9 and _ are allowed characters.\n");
660                                 return 1;
661                         }
662                 }
663
664                 if(mkdir(CONFDIR, 0755) && errno != EEXIST) {
665                         fprintf(stderr, "Could not create directory %s: %s\n", CONFDIR, strerror(errno));
666                         return 1;
667                 }
668
669                 if(mkdir(confbase, 0755) && errno != EEXIST) {
670                         fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
671                         return 1;
672                 }
673
674                 char *filename2 = NULL;
675                 xasprintf(&filename2, "%s/hosts", confbase);
676                 if(mkdir(filename2, 0755) && errno != EEXIST) {
677                         fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
678                         return 1;
679                 }
680
681                 FILE *f = fopen(filename, "w");
682                 if(!f) {
683                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
684                         return 1;
685                 }
686
687                 fprintf(f, "Name = %s\n", name);
688                 fclose(f);
689
690                 fclose(stdin);
691                 if(!rsa_keygen(2048) || !ecdsa_keygen())
692                         return false;
693
694                 return true;
695         }
696
697         /*
698          * Now handle commands that do involve connecting to a running tinc daemon.
699          * Authenticate the server by ensuring the parent directory can be
700          * traversed only by root. Note this is not totally race-free unless all
701          * ancestors are writable only by trusted users, which we don't verify.
702          */
703
704         FILE *f = fopen(pidfilename, "r");
705         if(!f) {
706                 fprintf(stderr, "Could not open pid file %s: %s\n", pidfilename, strerror(errno));
707                 return 1;
708         }
709         if(fscanf(f, "%20d %1024s %128s port %128s", &pid, controlcookie, host, port) != 4) {
710                 fprintf(stderr, "Could not parse pid file %s\n", pidfilename);
711                 return 1;
712         }
713
714 #ifdef HAVE_MINGW
715         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
716                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
717                 return 1;
718         }
719 #endif
720
721         struct addrinfo hints = {
722                 .ai_family = AF_UNSPEC,
723                 .ai_socktype = SOCK_STREAM,
724                 .ai_protocol = IPPROTO_TCP,
725                 .ai_flags = 0,
726         };
727
728         struct addrinfo *res = NULL;
729
730         if(getaddrinfo(host, port, &hints, &res) || !res) {
731                 fprintf(stderr, "Cannot resolve %s port %s: %s", host, port, strerror(errno));
732                 return 1;
733         }
734
735         fd = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
736         if(fd < 0) {
737                 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
738                 return 1;
739         }
740
741 #ifdef HAVE_MINGW
742         unsigned long arg = 0;
743
744         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
745                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
746         }
747 #endif
748
749         if(connect(fd, res->ai_addr, res->ai_addrlen) < 0) {
750                 fprintf(stderr, "Cannot connect to %s port %s: %s\n", host, port, sockstrerror(sockerrno));
751                 return 1;
752         }
753
754         freeaddrinfo(res);
755
756         char line[4096];
757         char data[4096];
758         int code, version, req;
759
760         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %s %d", &code, data, &version) != 3 || code != 0) {
761                 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
762                                 sockstrerror(sockerrno));
763                 return 1;
764         }
765
766         sendline(fd, "%d ^%s %d", ID, controlcookie, TINC_CTL_VERSION_CURRENT);
767         
768         if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &version, &pid) != 3 || code != 4 || version != TINC_CTL_VERSION_CURRENT) {
769                 fprintf(stderr, "Could not fully establish control socket connection\n");
770                 return 1;
771         }
772
773         if(!strcasecmp(argv[optind], "pid")) {
774                 printf("%d\n", pid);
775                 return 0;
776         }
777
778         if(!strcasecmp(argv[optind], "stop")) {
779 #ifndef HAVE_MINGW
780                 sendline(fd, "%d %d", CONTROL, REQ_STOP);
781                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_STOP || result) {
782                         fprintf(stderr, "Could not stop tinc daemon\n");
783                         return 1;
784                 }
785 #else
786                 if(!remove_service())
787                         return 1;
788 #endif
789                 return 0;
790         }
791
792         if(!strcasecmp(argv[optind], "reload")) {
793                 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
794                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RELOAD || result) {
795                         fprintf(stderr, "Could not reload tinc daemon\n");
796                         return 1;
797                 }
798                 return 0;
799         }
800
801         if(!strcasecmp(argv[optind], "restart")) {
802                 sendline(fd, "%d %d", CONTROL, REQ_RESTART);
803                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RESTART || result) {
804                         fprintf(stderr, "Could not restart tinc daemon\n");
805                         return 1;
806                 }
807                 return 0;
808         }
809
810         if(!strcasecmp(argv[optind], "retry")) {
811                 sendline(fd, "%d %d", CONTROL, REQ_RETRY);
812                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_RETRY || result) {
813                         fprintf(stderr, "Could not retry outgoing connections\n");
814                         return 1;
815                 }
816                 return 0;
817         }
818
819         if(!strcasecmp(argv[optind], "dump")) {
820                 if(argc < optind + 2) {
821                         fprintf(stderr, "Not enough arguments.\n");
822                         usage(true);
823                         return 1;
824                 }
825
826                 bool do_graph = false;
827
828                 if(!strcasecmp(argv[optind+1], "nodes"))
829                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
830                 else if(!strcasecmp(argv[optind+1], "edges"))
831                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
832                 else if(!strcasecmp(argv[optind+1], "subnets"))
833                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_SUBNETS);
834                 else if(!strcasecmp(argv[optind+1], "connections"))
835                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_CONNECTIONS);
836                 else if(!strcasecmp(argv[optind+1], "graph")) {
837                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
838                         sendline(fd, "%d %d", CONTROL, REQ_DUMP_EDGES);
839                         do_graph = true;
840                         printf("digraph {\n");
841                 } else {
842                         fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
843                         usage(true);
844                         return 1;
845                 }
846
847                 while(recvline(fd, line, sizeof line)) {
848                         char node1[4096], node2[4096];
849                         int n = sscanf(line, "%d %d %s to %s", &code, &req, node1, node2);
850                         if(n == 2) {
851                                 if(do_graph && req == REQ_DUMP_NODES)
852                                         continue;
853                                 else {
854                                         if(do_graph)
855                                                 printf("}\n");
856                                         return 0;
857                                 }
858                         }
859                         if(n < 2)
860                                 break;
861
862                         if(!do_graph)
863                                 printf("%s\n", line + 5);
864                         else {
865                                 if(req == REQ_DUMP_NODES)
866                                         printf(" %s [label = \"%s\"];\n", node1, node1);
867                                 else
868                                         printf(" %s -> %s;\n", node1, node2);
869                         }
870                 }
871
872                 fprintf(stderr, "Error receiving dump\n");
873                 return 1;
874         }
875
876         if(!strcasecmp(argv[optind], "purge")) {
877                 sendline(fd, "%d %d", CONTROL, REQ_PURGE);
878                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_PURGE || result) {
879                         fprintf(stderr, "Could not purge tinc daemon\n");
880                         return 1;
881                 }
882                 return 0;
883         }
884
885         if(!strcasecmp(argv[optind], "debug")) {
886                 int debuglevel, origlevel;
887
888                 if(argc != optind + 2) {
889                         fprintf(stderr, "Invalid arguments.\n");
890                         return 1;
891                 }
892                 debuglevel = atoi(argv[optind+1]);
893
894                 sendline(fd, "%d %d %d", CONTROL, REQ_SET_DEBUG, debuglevel);
895                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &origlevel) != 3 || code != CONTROL || req != REQ_SET_DEBUG) {
896                         fprintf(stderr, "Could not purge tinc daemon\n");
897                         return 1;
898                 }
899
900                 fprintf(stderr, "Old level %d, new level %d\n", origlevel, debuglevel);
901                 return 0;
902         }
903
904         if(!strcasecmp(argv[optind], "connect")) {
905                 if(argc != optind + 2) {
906                         fprintf(stderr, "Invalid arguments.\n");
907                         return 1;
908                 }
909                 char *name = argv[optind + 1];
910
911                 sendline(fd, "%d %d %s", CONTROL, REQ_CONNECT, name);
912                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_CONNECT || result) {
913                         fprintf(stderr, "Could not connect to %s\n", name);
914                         return 1;
915                 }
916                 return 0;
917         }
918
919         if(!strcasecmp(argv[optind], "disconnect")) {
920                 if(argc != optind + 2) {
921                         fprintf(stderr, "Invalid arguments.\n");
922                         return 1;
923                 }
924                 char *name = argv[optind + 1];
925
926                 sendline(fd, "%d %d %s", CONTROL, REQ_DISCONNECT, name);
927                 if(!recvline(fd, line, sizeof line) || sscanf(line, "%d %d %d", &code, &req, &result) != 3 || code != CONTROL || req != REQ_DISCONNECT || result) {
928                         fprintf(stderr, "Could not disconnect %s\n", name);
929                         return 1;
930                 }
931                 return 0;
932         }
933
934 #ifdef HAVE_CURSES
935         if(!strcasecmp(argv[optind], "top")) {
936                 top(fd);
937                 return 0;
938         }
939 #endif
940
941         if(!strcasecmp(argv[optind], "pcap")) {
942                 pcap(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : 0);
943                 return 0;
944         }
945
946         if(!strcasecmp(argv[optind], "log")) {
947                 logcontrol(fd, stdout, optind < argc - 1 ? atoi(argv[optind + 1]) : -1);
948                 return 0;
949         }
950
951         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
952         usage(true);
953         
954         close(fd);
955
956         return 0;
957 }