]> git.meshlink.io Git - meshlink/blob - src/tincctl.c
Small fixes to get really working control sockets on Windows.
[meshlink] / 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 = recv(fd, data + len, datalen - len, 0);
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         unsigned long arg = 0;
482
483         if(ioctlsocket(fd, FIONBIO, &arg) != 0) {
484                 fprintf(stderr, "ioctlsocket failed: %s", sockstrerror(sockerrno));
485         }
486 #else
487         struct sockaddr_un addr;
488         struct stat statbuf;
489         char *lastslash = strrchr(controlsocketname, '/');
490         if(lastslash != NULL) {
491                 /* control socket is not in cwd; stat its parent */
492                 *lastslash = 0;
493                 result = stat(controlsocketname, &statbuf);
494                 *lastslash = '/';
495         } else
496                 result = stat(".", &statbuf);
497
498         if(result < 0) {
499                 fprintf(stderr, "Unable to check control socket directory permissions: %s\n", strerror(errno));
500                 return 1;
501         }
502
503         if(statbuf.st_uid != 0 || (statbuf.st_mode & S_IXOTH) != 0 || (statbuf.st_gid != 0 && (statbuf.st_mode & S_IXGRP)) != 0) {
504                 fprintf(stderr, "Insecure permissions on control socket directory\n");
505                 return 1;
506         }
507
508         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
509                 fprintf(stderr, "Control socket filename too long!\n");
510                 return 1;
511         }
512
513         fd = socket(PF_UNIX, SOCK_STREAM, 0);
514         if(fd < 0) {
515                 fprintf(stderr, "Cannot create UNIX socket: %s\n", strerror(errno));
516                 return 1;
517         }
518
519         memset(&addr, 0, sizeof addr);
520         addr.sun_family = AF_UNIX;
521         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
522 #endif
523
524         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
525                         
526                 fprintf(stderr, "Cannot connect to %s: %s\n", controlsocketname, sockstrerror(sockerrno));
527                 return 1;
528         }
529
530         if(fullread(fd, &greeting, sizeof greeting) == -1) {
531                 fprintf(stderr, "Cannot read greeting from control socket: %s\n",
532                                 sockstrerror(sockerrno));
533                 return 1;
534         }
535
536         if(greeting.version != TINC_CTL_VERSION_CURRENT) {
537                 fprintf(stderr, "Version mismatch: server %d, client %d\n",
538                                 greeting.version, TINC_CTL_VERSION_CURRENT);
539                 return 1;
540         }
541
542         if(!strcasecmp(argv[optind], "pid")) {
543                 printf("%d\n", greeting.pid);
544                 return 0;
545         }
546
547         if(!strcasecmp(argv[optind], "stop")) {
548                 return send_ctl_request_cooked(fd, REQ_STOP, NULL, 0) != -1;
549         }
550
551         if(!strcasecmp(argv[optind], "reload")) {
552                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
553         }
554         
555         if(!strcasecmp(argv[optind], "restart")) {
556                 return send_ctl_request_cooked(fd, REQ_RESTART, NULL, 0) != -1;
557         }
558
559         if(!strcasecmp(argv[optind], "dump")) {
560                 if(argc < optind + 2) {
561                         fprintf(stderr, "Not enough arguments.\n");
562                         usage(true);
563                         return 1;
564                 }
565
566                 if(!strcasecmp(argv[optind+1], "nodes")) {
567                         return send_ctl_request_cooked(fd, REQ_DUMP_NODES, NULL, 0) != -1;
568                 }
569
570                 if(!strcasecmp(argv[optind+1], "edges")) {
571                         return send_ctl_request_cooked(fd, REQ_DUMP_EDGES, NULL, 0) != -1;
572                 }
573
574                 if(!strcasecmp(argv[optind+1], "subnets")) {
575                         return send_ctl_request_cooked(fd, REQ_DUMP_SUBNETS, NULL, 0) != -1;
576                 }
577
578                 if(!strcasecmp(argv[optind+1], "connections")) {
579                         return send_ctl_request_cooked(fd, REQ_DUMP_CONNECTIONS, NULL, 0) != -1;
580                 }
581
582                 if(!strcasecmp(argv[optind+1], "graph")) {
583                         return send_ctl_request_cooked(fd, REQ_DUMP_GRAPH, NULL, 0) != -1;
584                 }
585
586                 fprintf(stderr, "Unknown dump type '%s'.\n", argv[optind+1]);
587                 usage(true);
588                 return 1;
589         }
590
591         if(!strcasecmp(argv[optind], "purge")) {
592                 return send_ctl_request_cooked(fd, REQ_PURGE, NULL, 0) != -1;
593         }
594
595         if(!strcasecmp(argv[optind], "debug")) {
596                 int debuglevel;
597
598                 if(argc != optind + 2) {
599                         fprintf(stderr, "Invalid arguments.\n");
600                         return 1;
601                 }
602                 debuglevel = atoi(argv[optind+1]);
603                 return send_ctl_request_cooked(fd, REQ_SET_DEBUG, &debuglevel,
604                                                                            sizeof debuglevel) != -1;
605         }
606
607         if(!strcasecmp(argv[optind], "retry")) {
608                 return send_ctl_request_cooked(fd, REQ_RETRY, NULL, 0) != -1;
609         }
610
611         if(!strcasecmp(argv[optind], "reload")) {
612                 return send_ctl_request_cooked(fd, REQ_RELOAD, NULL, 0) != -1;
613         }
614
615         fprintf(stderr, "Unknown command `%s'.\n", argv[optind]);
616         usage(true);
617         
618         close(fd);
619
620         return 0;
621 }