Make sure the 1.1 branch compiles in a MinGW environment.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007-2009 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 "rsagen.h"
28 #include "utils.h"
29
30 /* The name this program was run with. */
31 char *program_name = NULL;
32
33 /* If nonzero, display usage information and exit. */
34 bool show_help = false;
35
36 /* If nonzero, print the version on standard output and exit.  */
37 bool show_version = false;
38
39 /* If nonzero, it will attempt to kill a running tincd and exit. */
40 int kill_tincd = 0;
41
42 /* If nonzero, generate public/private keypair for this host/net. */
43 int generate_keys = 0;
44
45 static char *identname = NULL;                          /* program name for syslog */
46 static char *controlsocketname = NULL;                  /* pid file location */
47 char *netname = NULL;
48 char *confbase = NULL;
49
50 #ifdef HAVE_MINGW
51 static struct WSAData wsa_state;
52 #endif
53
54 static struct option const long_options[] = {
55         {"config", required_argument, NULL, 'c'},
56         {"net", required_argument, NULL, 'n'},
57         {"help", no_argument, NULL, 1},
58         {"version", no_argument, NULL, 2},
59         {"controlsocket", required_argument, NULL, 5},
60         {NULL, 0, NULL, 0}
61 };
62
63 static void usage(bool status) {
64         if(status)
65                 fprintf(stderr, "Try `%s --help\' for more information.\n",
66                                 program_name);
67         else {
68                 printf("Usage: %s [options] command\n\n", program_name);
69                 printf("Valid options are:\n"
70                                 "  -c, --config=DIR              Read configuration options from DIR.\n"
71                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
72                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
73                                 "      --help                    Display this help and exit.\n"
74                                 "      --version                 Output version information and exit.\n"
75                                 "\n"
76                                 "Valid commands are:\n"
77                                 "  start                      Start tincd.\n"
78                                 "  stop                       Stop tincd.\n"
79                                 "  restart                    Restart tincd.\n"
80                                 "  reload                     Reload configuration of running tincd.\n"
81                                 "  pid                        Show PID of currently running tincd.\n"
82                                 "  generate-keys [bits]       Generate a new public/private keypair.\n"
83                                 "  dump                       Dump a list of one of the following things:\n"
84                                 "    nodes                    - all known nodes in the VPN\n"
85                                 "    edges                    - all known connections in the VPN\n"
86                                 "    subnets                  - all known subnets in the VPN\n"
87                                 "    connections              - all meta connections with ourself\n"
88                                 "    graph                    - graph of the VPN in dotty format\n"
89                                 "  purge                      Purge unreachable nodes\n"
90                                 "  debug N                    Set debug level\n"
91                                 "  retry                      Retry all outgoing connections\n"
92                                 "  reload                     Partial reload of configuration\n"
93                                 "\n");
94                 printf("Report bugs to tinc@tinc-vpn.org.\n");
95         }
96 }
97
98 static bool parse_options(int argc, char **argv) {
99         int r;
100         int option_index = 0;
101
102         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
103                 switch (r) {
104                         case 0:                         /* long option */
105                                 break;
106
107                         case 'c':                               /* config file */
108                                 confbase = xstrdup(optarg);
109                                 break;
110
111                         case 'n':                               /* net name given */
112                                 netname = xstrdup(optarg);
113                                 break;
114
115                         case 1:                                 /* show help */
116                                 show_help = true;
117                                 break;
118
119                         case 2:                                 /* show version */
120                                 show_version = true;
121                                 break;
122
123                         case 5:                                 /* open control socket here */
124                                 controlsocketname = xstrdup(optarg);
125                                 break;
126
127                         case '?':
128                                 usage(true);
129                                 return false;
130
131                         default:
132                                 break;
133                 }
134         }
135
136         return true;
137 }
138
139 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
140         FILE *r;
141         char *directory;
142         char buf[PATH_MAX];
143         char buf2[PATH_MAX];
144         size_t len;
145
146         /* Check stdin and stdout */
147         if(isatty(0) && isatty(1)) {
148                 /* Ask for a file and/or directory name. */
149                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
150                                 what, filename);
151                 fflush(stdout);
152
153                 if(fgets(buf, sizeof buf, stdin) < 0) {
154                         fprintf(stderr, "Error while reading stdin: %s\n",
155                                         strerror(errno));
156                         return NULL;
157                 }
158
159                 len = strlen(buf);
160                 if(len)
161                         buf[--len] = 0;
162
163                 if(len)
164                         filename = buf;
165         }
166
167 #ifdef HAVE_MINGW
168         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
169 #else
170         if(filename[0] != '/') {
171 #endif
172                 /* The directory is a relative path or a filename. */
173                 directory = get_current_dir_name();
174                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
175                 filename = buf2;
176         }
177
178         umask(0077);                            /* Disallow everything for group and other */
179
180         /* Open it first to keep the inode busy */
181
182         r = fopen(filename, mode);
183
184         if(!r) {
185                 fprintf(stderr, "Error opening file `%s': %s\n", filename, strerror(errno));
186                 return NULL;
187         }
188
189         return r;
190 }
191
192 /*
193   Generate a public/private RSA keypair, and ask for a file to store
194   them in.
195 */
196 static bool keygen(int bits) {
197         rsa_t key;
198         FILE *f;
199         char *name = NULL;
200         char *filename;
201
202         fprintf(stderr, "Generating %d bits keys:\n", bits);
203
204         if(!rsa_generate(&key, bits, 0x10001)) {
205                 fprintf(stderr, "Error during key generation!\n");
206                 return false;
207         } else
208                 fprintf(stderr, "Done.\n");
209
210         xasprintf(&filename, "%s/rsa_key.priv", confbase);
211         f = ask_and_open(filename, "private RSA key", "a");
212
213         if(!f)
214                 return false;
215   
216 #ifdef HAVE_FCHMOD
217         /* Make it unreadable for others. */
218         fchmod(fileno(f), 0600);
219 #endif
220                 
221         if(ftell(f))
222                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
223
224         rsa_write_pem_private_key(&key, f);
225
226         fclose(f);
227         free(filename);
228
229         if(name)
230                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
231         else
232                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
233
234         f = ask_and_open(filename, "public RSA key", "a");
235
236         if(!f)
237                 return false;
238
239         if(ftell(f))
240                 fprintf(stderr, "Appending key to existing contents.\nMake sure only one key is stored in the file.\n");
241
242         rsa_write_pem_public_key(&key, f);
243
244         fclose(f);
245         free(filename);
246
247         return true;
248 }
249
250 /*
251   Set all files and paths according to netname
252 */
253 static void make_names(void) {
254 #ifdef HAVE_MINGW
255         HKEY key;
256         char installdir[1024] = "";
257         long len = sizeof installdir;
258 #endif
259
260         if(netname)
261                 xasprintf(&identname, "tinc.%s", netname);
262         else
263                 identname = xstrdup("tinc");
264
265 #ifdef HAVE_MINGW
266         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
267                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
268                         if(!confbase) {
269                                 if(netname)
270                                         xasprintf(&confbase, "%s/%s", installdir, netname);
271                                 else
272                                         xasprintf(&confbase, "%s", installdir);
273                         }
274                 }
275                 RegCloseKey(key);
276                 if(*installdir)
277                         return;
278         }
279 #endif
280
281         if(!controlsocketname)
282                 xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
283
284         if(netname) {
285                 if(!confbase)
286                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
287                 else
288                         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
289         } else {
290                 if(!confbase)
291                         xasprintf(&confbase, CONFDIR "/tinc");
292         }
293 }
294
295 static int fullread(int fd, void *data, size_t datalen) {
296         int rv, len = 0;
297
298         while(len < datalen) {
299                 rv = read(fd, data + len, datalen - len);
300                 if(rv == -1 && errno == EINTR)
301                         continue;
302                 else if(rv == -1)
303                         return rv;
304                 else if(rv == 0) {
305 #ifdef HAVE_MINGW
306                         errno = 0;
307 #else
308                         errno = ENODATA;
309 #endif
310                         return -1;
311                 }
312                 len += rv;
313         }
314         return 0;
315 }
316
317 /*
318    Send a request (raw)
319 */
320 static int send_ctl_request(int fd, enum request_type type,
321                                                    void const *outdata, size_t outdatalen,
322                                                    int *res_errno_p, void **indata_p,
323                                                    size_t *indatalen_p) {
324         tinc_ctl_request_t req;
325         int rv;
326         void *indata;
327
328         memset(&req, 0, sizeof req);
329         req.length = sizeof req + outdatalen;
330         req.type = type;
331         req.res_errno = 0;
332
333 #ifdef HAVE_MINGW
334         if(send(fd, (void *)&req, sizeof req, 0) != sizeof req || send(fd, outdata, outdatalen, 0) != outdatalen)
335                 return -1;
336 #else
337         struct iovec vector[2] = {
338                 {&req, sizeof req},
339                 {(void*) outdata, outdatalen}
340         };
341
342         if(res_errno_p == NULL)
343                 return -1;
344
345         while((rv = writev(fd, vector, 2)) == -1 && errno == EINTR) ;
346         if(rv != req.length)
347                 return -1;
348 #endif
349
350         if(fullread(fd, &req, sizeof req) == -1)
351                 return -1;
352
353         if(req.length < sizeof req) {
354                 errno = EINVAL;
355                 return -1;
356         }
357
358         if(req.length > sizeof req) {
359                 if(indata_p == NULL) {
360                         errno = EINVAL;
361                         return -1;
362                 }
363
364                 indata = xmalloc(req.length - sizeof req);
365
366                 if(fullread(fd, indata, req.length - sizeof req) == -1) {
367                         free(indata);
368                         return -1;
369                 }
370
371                 *indata_p = indata;
372                 if(indatalen_p != NULL)
373                         *indatalen_p = req.length - sizeof req;
374         }
375
376         *res_errno_p = req.res_errno;
377
378         return 0;
379 }
380
381 /*
382    Send a request (with printfs)
383 */
384 static int send_ctl_request_cooked(int fd, enum request_type type, void const *outdata, size_t outdatalen) {
385         int res_errno = -1;
386         char *buf = NULL;
387         size_t buflen = 0;
388
389         if(send_ctl_request(fd, type, outdata, outdatalen, &res_errno,
390                                                 (void**) &buf, &buflen)) {
391                 fprintf(stderr, "Error sending request: %s\n", strerror(errno));
392                 return -1;
393         }
394
395         if(buf != NULL) {
396                 printf("%*s", (int)buflen, buf);
397                 free(buf);
398         }
399
400         if(res_errno != 0) {
401                 fprintf(stderr, "Server reported error: %s\n", strerror(res_errno));
402                 return -1;
403         }
404
405         return 0;
406 }
407
408 int main(int argc, char *argv[], char *envp[]) {
409         tinc_ctl_greeting_t greeting;
410         int fd;
411         int result;
412
413         program_name = argv[0];
414
415         if(!parse_options(argc, argv))
416                 return 1;
417         
418         make_names();
419
420         if(show_version) {
421                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
422                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
423                 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
424                                 "See the AUTHORS file for a complete list.\n\n"
425                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
426                                 "and you are welcome to redistribute it under certain conditions;\n"
427                                 "see the file COPYING for details.\n");
428
429                 return 0;
430         }
431
432         if(show_help) {
433                 usage(false);
434                 return 0;
435         }
436
437         if(optind >= argc) {
438                 fprintf(stderr, "Not enough arguments.\n");
439                 usage(true);
440                 return 1;
441         }
442
443         // First handle commands that don't involve connecting to a running tinc daemon.
444
445         if(!strcasecmp(argv[optind], "generate-keys")) {
446                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 2048);
447         }
448
449         if(!strcasecmp(argv[optind], "start")) {
450                 argv[optind] = NULL;
451                 execve(SBINDIR "/tincd", argv, envp);
452                 fprintf(stderr, "Could not start tincd: %s", strerror(errno));
453                 return 1;
454         }
455
456         /*
457          * Now handle commands that do involve connecting to a running tinc daemon.
458          * Authenticate the server by ensuring the parent directory can be
459          * traversed only by root. Note this is not totally race-free unless all
460          * ancestors are writable only by trusted users, which we don't verify.
461          */
462
463 #ifdef HAVE_MINGW
464         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
465                 fprintf(stderr, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
466                 return 1;
467         }
468
469         struct sockaddr_in addr;
470         memset(&addr, 0, sizeof addr);
471         addr.sin_family = AF_INET;
472         addr.sin_addr.s_addr = htonl(0x7f000001);
473         addr.sin_port = htons(55555);
474
475         fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
476         if(fd < 0) {
477                 fprintf(stderr, "Cannot create TCP socket: %s\n", sockstrerror(sockerrno));
478                 return 1;
479         }
480
481         fprintf(stderr, "Got socket %d\n", fd);
482
483         unsigned long arg = 0;
484
485         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
486                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
487         }
488 #else
489         struct sockaddr_un addr;
490         struct stat statbuf;
491         char *lastslash = strrchr(controlsocketname, '/');
492         if(lastslash != NULL) {
493                 /* control socket is not in cwd; stat its parent */
494                 *lastslash = 0;
495                 result = stat(controlsocketname, &statbuf);
496                 *lastslash = '/';
497         } else
498                 result = stat(".", &statbuf);
499
500         if(result < 0) {
501                 fprintf(stderr, "Unable to check control socket directory permissions: %s\n", strerror(errno));
502                 return 1;
503         }
504
505         if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
506                 fprintf(stderr, "Insecure permissions on control socket directory\n");
507                 return 1;
508         }
509
510         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
511                 fprintf(stderr, "Control socket filename too long!\n");
512                 return 1;
513         }
514
515         fd = socket(PF_UNIX, SOCK_STREAM, 0);
516         if(fd < 0) {
517                 fprintf(stderr, "Cannot create UNIX socket: %s\n", strerror(errno));
518                 return 1;
519         }
520
521         memset(&addr, 0, sizeof addr);
522         addr.sun_family = AF_UNIX;
523         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
524 #endif
525
526         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
527                         
528                 fprintf(stderr, "Cannot connect to %s: %s\n", controlsocketname, sockstrerror(sockerrno));
529                 return 1;
530         }
531
532         fprintf(stderr, "Connected!\n");
533
534         if(fullread(fd, &greeting, sizeof greeting) == -1) {
535                 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
536                                 sockstrerror(sockerrno));
537                 return 1;
538         }
539
540         if(greeting.version != TINC_CTL_VERSION_CURRENT) {
541                 fprintf(stderr, "Version mismatch: server %d, client %d\n",
542                                 greeting.version, TINC_CTL_VERSION_CURRENT);
543                 return 1;
544         }
545
546         if(!strcasecmp(argv[optind], "pid")) {
547                 printf("%d\n", greeting.pid);
548                 return 0;
549         }
550
551         if(!strcasecmp(argv[optind], "stop")) {
552                 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
553         }
554
555         if(!strcasecmp(argv[optind], "reload")) {
556                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
557         }
558         
559         if(!strcasecmp(argv[optind], "restart")) {
560                 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
561         }
562
563         if(!strcasecmp(argv[optind], "dump")) {
564                 if(argc < optind + 2) {
565                         fprintf(stderr, "Not enough arguments.\n");
566                         usage(true);
567                         return 1;
568                 }
569
570                 if(!strcasecmp(argv[optind+1], "nodes")) {
571                         return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
572                 }
573
574                 if(!strcasecmp(argv[optind+1], "edges")) {
575                         return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
576                 }
577
578                 if(!strcasecmp(argv[optind+1], "subnets")) {
579                         return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
580                 }
581
582                 if(!strcasecmp(argv[optind+1], "connections")) {
583                         return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
584                 }
585
586                 if(!strcasecmp(argv[optind+1], "graph")) {
587                         return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
588                 }
589
590                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
591                 usage(true);
592                 return 1;
593         }
594
595         if(!strcasecmp(argv[optind], "purge")) {
596                 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
597         }
598
599         if(!strcasecmp(argv[optind], "debug")) {
600                 int debuglevel;
601
602                 if(argc != optind + 2) {
603                         fprintf(stderr, "Invalid arguments.\n");
604                         return 1;
605                 }
606                 debuglevel = atoi(argv[optind+1]);
607                 return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
608                                                                            sizeof debuglevel) != -1;
609         }
610
611         if(!strcasecmp(argv[optind], "retry")) {
612                 return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
613         }
614
615         if(!strcasecmp(argv[optind], "reload")) {
616                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
617         }
618
619         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
620         usage(true);
621         
622         close(fd);
623
624         return 0;
625 }