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