Implement "stop" command, and allow tincctl to retrieve a running tincd's PID.
[tinc] / src / tincctl.c
1 /*
2     tincctl.c -- Controlling a running tincd
3     Copyright (C) 2007 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
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19     $Id$
20 */
21
22 #include "system.h"
23
24 #include <sys/un.h>
25 #include <openssl/rand.h>
26 #include <openssl/rsa.h>
27 #include <openssl/pem.h>
28 #include <openssl/evp.h>
29 #include <openssl/engine.h>
30
31 #include <getopt.h>
32
33 #include "protocol.h"
34 #include "xalloc.h"
35
36 /* The name this program was run with. */
37 char *program_name = NULL;
38
39 /* If nonzero, display usage information and exit. */
40 bool show_help = false;
41
42 /* If nonzero, print the version on standard output and exit.  */
43 bool show_version = false;
44
45 /* If nonzero, it will attempt to kill a running tincd and exit. */
46 int kill_tincd = 0;
47
48 /* If nonzero, generate public/private keypair for this host/net. */
49 int generate_keys = 0;
50
51 static char *identname = NULL;                          /* program name for syslog */
52 static char *controlsocketname = NULL;                  /* pid file location */
53 char *netname = NULL;
54 char *confbase = NULL;
55
56 static struct option const long_options[] = {
57         {"config", required_argument, NULL, 'c'},
58         {"net", required_argument, NULL, 'n'},
59         {"help", no_argument, NULL, 1},
60         {"version", no_argument, NULL, 2},
61         {"controlsocket", required_argument, NULL, 5},
62         {NULL, 0, NULL, 0}
63 };
64
65 static void usage(bool status) {
66         if(status)
67                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
68                                 program_name);
69         else {
70                 printf(_("Usage: %s [options] command\n\n"), program_name);
71                 printf(_("Valid options are:\n"
72                                 "  -c, --config=DIR              Read configuration options from DIR.\n"
73                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
74                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
75                                 "      --help                    Display this help and exit.\n"
76                                 "      --version                 Output version information and exit.\n"
77                                 "\n"
78                                 "Valid commands are:\n"
79                                 "  start                      Start tincd.\n"
80                                 "  stop                       Stop tincd.\n"
81                                 "  restart                    Restart tincd.\n"
82                                 "  reload                     Reload configuration of running tincd.\n"
83                                 "  pid                        Show PID of currently running tincd.\n"
84                                 "  generate-keys [bits]       Generate a new 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                                 "\n"));
92                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
93         }
94 }
95
96 static bool parse_options(int argc, char **argv) {
97         int r;
98         int option_index = 0;
99
100         while((r = getopt_long(argc, argv, "c:n:", long_options, &option_index)) != EOF) {
101                 switch (r) {
102                         case 0:                         /* long option */
103                                 break;
104
105                         case 'c':                               /* config file */
106                                 confbase = xstrdup(optarg);
107                                 break;
108
109                         case 'n':                               /* net name given */
110                                 netname = xstrdup(optarg);
111                                 break;
112
113                         case 1:                                 /* show help */
114                                 show_help = true;
115                                 break;
116
117                         case 2:                                 /* show version */
118                                 show_version = true;
119                                 break;
120
121                         case 5:                                 /* open control socket here */
122                                 controlsocketname = xstrdup(optarg);
123                                 break;
124
125                         case '?':
126                                 usage(true);
127                                 return false;
128
129                         default:
130                                 break;
131                 }
132         }
133
134         return true;
135 }
136
137 FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
138         FILE *r;
139         char *directory;
140         char buf[PATH_MAX];
141         char buf2[PATH_MAX];
142         size_t len;
143
144         /* Check stdin and stdout */
145         if(isatty(0) && isatty(1)) {
146                 /* Ask for a file and/or directory name. */
147                 fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
148                                 what, filename);
149                 fflush(stdout);
150
151                 if(fgets(buf, sizeof buf, stdin) < 0) {
152                         fprintf(stderr, _("Error while reading stdin: %s\n"),
153                                         strerror(errno));
154                         return NULL;
155                 }
156
157                 len = strlen(buf);
158                 if(len)
159                         buf[--len] = 0;
160
161                 if(len)
162                         filename = buf;
163         }
164
165 #ifdef HAVE_MINGW
166         if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
167 #else
168         if(filename[0] != '/') {
169 #endif
170                 /* The directory is a relative path or a filename. */
171                 directory = get_current_dir_name();
172                 snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
173                 filename = buf2;
174         }
175
176         umask(0077);                            /* Disallow everything for group and other */
177
178         /* Open it first to keep the inode busy */
179
180         r = fopen(filename, mode);
181
182         if(!r) {
183                 fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
184                 return NULL;
185         }
186
187         return r;
188 }
189
190 /* This function prettyprints the key generation process */
191
192 static void indicator(int a, int b, void *p) {
193         switch (a) {
194                 case 0:
195                         fprintf(stderr, ".");
196                         break;
197
198                 case 1:
199                         fprintf(stderr, "+");
200                         break;
201
202                 case 2:
203                         fprintf(stderr, "-");
204                         break;
205
206                 case 3:
207                         switch (b) {
208                                 case 0:
209                                         fprintf(stderr, " p\n");
210                                         break;
211
212                                 case 1:
213                                         fprintf(stderr, " q\n");
214                                         break;
215
216                                 default:
217                                         fprintf(stderr, "?");
218                         }
219                         break;
220
221                 default:
222                         fprintf(stderr, "?");
223         }
224 }
225
226 /*
227   Generate a public/private RSA keypair, and ask for a file to store
228   them in.
229 */
230 static bool keygen(int bits) {
231         RSA *rsa_key;
232         FILE *f;
233         char *name = NULL;
234         char *filename;
235
236         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
237         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
238
239         if(!rsa_key) {
240                 fprintf(stderr, _("Error during key generation!\n"));
241                 return false;
242         } else
243                 fprintf(stderr, _("Done.\n"));
244
245         asprintf(&filename, "%s/rsa_key.priv", confbase);
246         f = ask_and_open(filename, _("private RSA key"), "a");
247
248         if(!f)
249                 return false;
250   
251 #ifdef HAVE_FCHMOD
252         /* Make it unreadable for others. */
253         fchmod(fileno(f), 0600);
254 #endif
255                 
256         if(ftell(f))
257                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
258
259         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
260         fclose(f);
261         free(filename);
262
263         if(name)
264                 asprintf(&filename, "%s/hosts/%s", confbase, name);
265         else
266                 asprintf(&filename, "%s/rsa_key.pub", confbase);
267
268         f = ask_and_open(filename, _("public RSA key"), "a");
269
270         if(!f)
271                 return false;
272
273         if(ftell(f))
274                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
275
276         PEM_write_RSAPublicKey(f, rsa_key);
277         fclose(f);
278         free(filename);
279
280         return true;
281 }
282
283 /*
284   Set all files and paths according to netname
285 */
286 static void make_names(void) {
287 #ifdef HAVE_MINGW
288         HKEY key;
289         char installdir[1024] = "";
290         long len = sizeof(installdir);
291 #endif
292
293         if(netname)
294                 asprintf(&identname, "tinc.%s", netname);
295         else
296                 identname = xstrdup("tinc");
297
298 #ifdef HAVE_MINGW
299         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
300                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
301                         if(!logfilename)
302                                 asprintf(&logfilename, "%s/log/%s.log", identname);
303                         if(!confbase) {
304                                 if(netname)
305                                         asprintf(&confbase, "%s/%s", installdir, netname);
306                                 else
307                                         asprintf(&confbase, "%s", installdir);
308                         }
309                 }
310                 RegCloseKey(key);
311                 if(*installdir)
312                         return;
313         }
314 #endif
315
316         if(!controlsocketname)
317                 asprintf(&controlsocketname, LOCALSTATEDIR "/run/%s.control", identname);
318
319         if(netname) {
320                 if(!confbase)
321                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
322                 else
323                         fprintf(stderr, _("Both netname and configuration directory given, using the latter...\n"));
324         } else {
325                 if(!confbase)
326                         asprintf(&confbase, CONFDIR "/tinc");
327         }
328 }
329
330 int main(int argc, char *argv[], char *envp[]) {
331         int fd;
332         struct sockaddr_un addr;
333         program_name = argv[0];
334
335         setlocale(LC_ALL, "");
336         bindtextdomain(PACKAGE, LOCALEDIR);
337         textdomain(PACKAGE);
338
339         if(!parse_options(argc, argv))
340                 return 1;
341         
342         make_names();
343
344         if(show_version) {
345                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
346                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
347                 printf(_("Copyright (C) 1998-2007 Ivo Timmermans, Guus Sliepen and others.\n"
348                                 "See the AUTHORS file for a complete list.\n\n"
349                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
350                                 "and you are welcome to redistribute it under certain conditions;\n"
351                                 "see the file COPYING for details.\n"));
352
353                 return 0;
354         }
355
356         if(show_help) {
357                 usage(false);
358                 return 0;
359         }
360
361         if(optind >= argc) {
362                 fprintf(stderr, _("Not enough arguments.\n"));
363                 usage(true);
364                 return 1;
365         }
366
367         // First handle commands that don't involve connecting to a running tinc daemon.
368
369         if(!strcasecmp(argv[optind], "generate-keys")) {
370                 return !keygen(optind > argc ? atoi(argv[optind + 1]) : 1024);
371         }
372
373         if(!strcasecmp(argv[optind], "start")) {
374                 argv[optind] = NULL;
375                 execve("tincd", argv, envp);
376                 fprintf(stderr, _("Could not start tincd: %s"), strerror(errno));
377                 return 1;
378         }
379
380         // Now handle commands that do involve connecting to a running tinc daemon.
381
382         if(strlen(controlsocketname) >= sizeof addr.sun_path) {
383                 fprintf(stderr, _("Control socket filename too long!\n"));
384                 return 1;
385         }
386
387         fd = socket(PF_UNIX, SOCK_STREAM, 0);
388         if(fd < 0) {
389                 fprintf(stderr, _("Cannot create UNIX socket: %s\n"), strerror(errno));
390                 return 1;
391         }
392
393         memset(&addr, 0, sizeof addr);
394         addr.sun_family = AF_UNIX;
395         strncpy(addr.sun_path, controlsocketname, sizeof addr.sun_path - 1);
396
397         if(connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
398                 fprintf(stderr, _("Cannot connect to %s: %s\n"), controlsocketname, strerror(errno));
399                 return 1;
400         }
401
402         struct ucred cred;
403         socklen_t credlen = sizeof cred;
404
405         if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &credlen) < 0) {
406                 fprintf(stderr, _("Could not obtain PID: %s\n"), strerror(errno));
407                 return 1;
408         }
409
410         if(!strcasecmp(argv[optind], "pid")) {
411                 printf("%d\n", cred.pid);
412                 return 0;
413         }
414
415         if(!strcasecmp(argv[optind], "stop")) {
416                 write(fd, "stop\n", 5);
417                 return 0;
418         }
419
420         if(!strcasecmp(argv[optind], "reload")) {
421                 write(fd, "reload\n", 7);
422                 return 0;
423         }
424         
425         if(!strcasecmp(argv[optind], "restart")) {
426                 write(fd, "restart\n", 8);
427                 return 0;
428         }
429
430         fprintf(stderr, _("Unknown command `%s'.\n"), argv[optind]);
431         usage(true);
432         
433         close(fd);
434
435         return 0;
436 }