Write public key to rsa_key.pub instead of rsa_key.priv (if not host
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2001 Ivo Timmermans <itimmermans@bigfoot.com>
4                   2000,2001 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: tincd.c,v 1.10.4.51 2001/07/24 20:04:22 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h> 
27 #include <getopt.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <syslog.h>
32 #include <unistd.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <termios.h>
36
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40
41 #include <openssl/rand.h>
42 #include <openssl/rsa.h>
43 #include <openssl/pem.h>
44
45 #include <utils.h>
46 #include <xalloc.h>
47
48 #include "conf.h"
49 #include "net.h"
50 #include "netutl.h"
51 #include "process.h"
52 #include "protocol.h"
53 #include "subnet.h"
54
55 #include "system.h"
56
57 /* The name this program was run with. */
58 char *program_name;
59
60 /* If nonzero, display usage information and exit. */
61 static int show_help;
62
63 /* If nonzero, print the version on standard output and exit.  */
64 static int show_version;
65
66 /* If nonzero, it will attempt to kill a running tincd and exit. */
67 static int kill_tincd = 0;
68
69 /* If nonzero, generate public/private keypair for this host/net. */
70 static int generate_keys = 0;
71
72 char *identname;                 /* program name for syslog */
73 char *pidfilename;               /* pid file location */
74 char **g_argv;                   /* a copy of the cmdline arguments */
75 char **environment;              /* A pointer to the environment on
76                                     startup */
77
78 static struct option const long_options[] =
79 {
80   { "config", required_argument, NULL, 'c' },
81   { "kill", no_argument, NULL, 'k' },
82   { "net", required_argument, NULL, 'n' },
83   { "help", no_argument, &show_help, 1 },
84   { "version", no_argument, &show_version, 1 },
85   { "no-detach", no_argument, &do_detach, 0 },
86   { "generate-keys", optional_argument, NULL, 'K'},
87   { NULL, 0, NULL, 0 }
88 };
89
90 static void
91 usage(int status)
92 {
93   if(status != 0)
94     fprintf(stderr, _("Try `%s --help\' for more information.\n"), program_name);
95   else
96     {
97       printf(_("Usage: %s [option]...\n\n"), program_name);
98       printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
99                "  -D, --no-detach            Don't fork and detach.\n"
100                "  -d                         Increase debug level.\n"
101                "  -k, --kill                 Attempt to kill a running tincd and exit.\n"
102                "  -n, --net=NETNAME          Connect to net NETNAME.\n"));
103       printf(_("  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
104                "      --help                 Display this help and exit.\n"
105                "      --version              Output version information and exit.\n\n"));
106       printf(_("Report bugs to tinc@nl.linux.org.\n"));
107     }
108   exit(status);
109 }
110
111 void
112 parse_options(int argc, char **argv, char **envp)
113 {
114   int r;
115   int option_index = 0;
116   
117   while((r = getopt_long(argc, argv, "c:Ddkn:K::", long_options, &option_index)) != EOF)
118     {
119       switch(r)
120         {
121         case 0: /* long option */
122           break;
123         case 'c': /* config file */
124           confbase = xmalloc(strlen(optarg)+1);
125           strcpy(confbase, optarg);
126           break;
127         case 'D': /* no detach */
128           do_detach = 0;
129           break;
130         case 'd': /* inc debug level */
131           if(optarg)
132             debug_lvl = atoi(optarg);
133           else
134             debug_lvl++;
135           break;
136         case 'k': /* kill old tincds */
137           kill_tincd = 1;
138           break;
139         case 'n': /* net name given */
140           netname = xmalloc(strlen(optarg)+1);
141           strcpy(netname, optarg);
142           break;
143         case 'K': /* generate public/private keypair */
144           if(optarg)
145             {
146               generate_keys = atoi(optarg);
147               if(generate_keys < 512)
148                 {
149                   fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
150                           optarg);
151                   usage(1);
152                 }
153               generate_keys &= ~7;      /* Round it to bytes */
154             }
155           else
156             generate_keys = 1024;
157           break;
158         case '?':
159           usage(1);
160         default:
161           break;
162         }
163     }
164 }
165
166 /* This function prettyprints the key generation process */
167
168 void indicator(int a, int b, void *p)
169 {
170   switch(a)
171   {
172     case 0:
173       fprintf(stderr, ".");
174       break;
175     case 1:
176       fprintf(stderr, "+");
177       break;
178     case 2:
179       fprintf(stderr, "-");
180       break;
181     case 3:
182       switch(b)
183         {
184           case 0:
185             fprintf(stderr, " p\n");      
186             break;
187           case 1:
188             fprintf(stderr, " q\n");
189             break;
190           default:
191             fprintf(stderr, "?");
192          }
193        break;
194     default:
195       fprintf(stderr, "?");
196   }
197 }
198
199 /*
200   Generate a public/private RSA keypair, and ask for a file to store
201   them in.
202 */
203 int keygen(int bits)
204 {
205   RSA *rsa_key;
206   FILE *f;
207   config_t const *cfg;
208   char *filename;
209
210   fprintf(stderr, _("Generating %d bits keys:\n"), bits);
211   rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
212
213   if(!rsa_key)
214     {
215       fprintf(stderr, _("Error during key generation!\n"));
216       return -1;
217      }
218   else
219     fprintf(stderr, _("Done.\n"));
220
221   if(config && (cfg = get_config_val(config, config_name)))
222     asprintf(&filename, "%s/hosts/%s", confbase, cfg->data.ptr);
223   else
224     asprintf(&filename, "%s/rsa_key.pub", confbase);
225
226   if((f = ask_and_safe_open(filename, _("public RSA key"), "a")) == NULL)
227     return -1;
228
229   if(ftell(f))
230     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
231
232   PEM_write_RSAPublicKey(f, rsa_key);
233   fclose(f);
234   free(filename);
235   
236   asprintf(&filename, "%s/rsa_key.priv", confbase);
237   if((f = ask_and_safe_open(filename, _("private RSA key"), "a")) == NULL)
238     return -1;
239
240   if(ftell(f))
241     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
242
243   PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
244   fclose(f);
245   free(filename);
246
247   return 0;
248 }
249
250 /*
251   Set all files and paths according to netname
252 */
253 void make_names(void)
254 {
255   if(netname)
256     {
257       if(!pidfilename)
258         asprintf(&pidfilename, LOCALSTATEDIR "/run/tinc.%s.pid", netname);
259       if(!confbase)
260         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
261       else
262         syslog(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
263       if(!identname)
264         asprintf(&identname, "tinc.%s", netname);
265     }
266   else
267     {
268       if(!pidfilename)
269         pidfilename = LOCALSTATEDIR "/run/tinc.pid";
270       if(!confbase)
271         asprintf(&confbase, "%s/tinc", CONFDIR);
272       if(!identname)
273         identname = "tinc";
274     }
275 }
276
277 int
278 main(int argc, char **argv, char **envp)
279 {
280   program_name = argv[0];
281
282   setlocale (LC_ALL, "");
283   bindtextdomain (PACKAGE, LOCALEDIR);
284   textdomain (PACKAGE);
285
286   environment = envp;
287   parse_options(argc, argv, envp);
288
289   if(show_version)
290     {
291       printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE, VERSION, __DATE__, __TIME__, PROT_CURRENT);
292       printf(_("Copyright (C) 1998-2001 Ivo Timmermans, Guus Sliepen and others.\n"
293                "See the AUTHORS file for a complete list.\n\n"
294                "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
295                "and you are welcome to redistribute it under certain conditions;\n"
296                "see the file COPYING for details.\n"));
297
298       return 0;
299     }
300
301   if(show_help)
302     usage(0);
303
304   if(geteuid())
305     {
306       fprintf(stderr, _("You must be root to run this program.\n"));
307       return 1;
308     }
309
310 #ifdef HAVE_SOLARIS
311   openlog("tinc", LOG_CONS, LOG_DAEMON);        /* Catch all syslog() calls issued before detaching */
312 #else  
313   openlog("tinc", LOG_PERROR, LOG_DAEMON);      /* Catch all syslog() calls issued before detaching */
314 #endif
315
316   g_argv = argv;
317
318   make_names();
319
320   /* Slllluuuuuuurrrrp! */
321 cp
322   RAND_load_file("/dev/urandom", 1024);
323 cp
324   if(generate_keys)
325     {
326       read_server_config();
327       exit(keygen(generate_keys));
328     }
329     
330   if(kill_tincd)
331     exit(kill_other());
332
333   if(read_server_config())
334     exit(1);
335 cp
336   if(detach())
337     exit(0);
338 cp
339   for(;;)
340     {
341       if(!setup_network_connections())
342         {
343           main_loop();
344           cleanup_and_exit(1);
345         }
346       
347       syslog(LOG_ERR, _("Unrecoverable error"));
348       cp_trace();
349
350       if(do_detach)
351         {
352           syslog(LOG_NOTICE, _("Restarting in %d seconds!"), MAXTIMEOUT);
353           sleep(MAXTIMEOUT);
354         }
355       else
356         {
357           syslog(LOG_ERR, _("Not restarting."));
358           exit(1);
359         }
360     }
361 }