Another file moved; random interface stuff.
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2002 Ivo Timmermans <itimmermans@bigfoot.com>
4                   2000-2002 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.16 2002/05/02 11:50:07 zarq 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 <unistd.h>
32 #include <signal.h>
33 #include <string.h>
34 #include <termios.h>
35
36 #ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
38 #endif
39
40 #ifdef USE_OPENSSL
41 #include <openssl/rand.h>
42 #include <openssl/rsa.h>
43 #include <openssl/pem.h>
44 #include <openssl/evp.h>
45 #endif
46
47 #ifdef USE_GCRYPT
48 #include <gcrypt.h>
49 #endif
50
51 #include <utils.h>
52 #include <xalloc.h>
53
54 #include "callbacks.h"
55 #include "read_conf.h"
56 #include "net.h"
57 #include "netutl.h"
58 #include "process.h"
59 #include "protocol.h"
60 #include "subnet.h"
61 #include "logging.h"
62
63 #include "system.h"
64
65 /* The name this program was run with. */
66 char *program_name;
67
68 /* If nonzero, display usage information and exit. */
69 int show_help;
70
71 /* If nonzero, print the version on standard output and exit.  */
72 int show_version;
73
74 /* If nonzero, it will attempt to kill a running tincd and exit. */
75 int kill_tincd = 0;
76
77 /* If nonzero, generate public/private keypair for this host/net. */
78 int generate_keys = 0;
79
80 /* If nonzero, use null ciphers and skip all key exchanges. */
81 int bypass_security = 0;
82
83 char *identname;                 /* program name for syslog */
84 char *pidfilename;               /* pid file location */
85 char **g_argv;                   /* a copy of the cmdline arguments */
86 char **environment;              /* A pointer to the environment on
87                                     startup */
88
89 static struct option const long_options[] =
90 {
91   { "config", required_argument, NULL, 'c' },
92   { "kill", optional_argument, NULL, 'k' },
93   { "net", required_argument, NULL, 'n' },
94   { "help", no_argument, &show_help, 1 },
95   { "version", no_argument, &show_version, 1 },
96   { "no-detach", no_argument, &do_detach, 0 },
97   { "generate-keys", optional_argument, NULL, 'K'},
98   { "debug", optional_argument, NULL, 'd'},
99   { "bypass-security", no_argument, &bypass_security, 1 },
100   { NULL, 0, NULL, 0 }
101 };
102
103 static void
104 usage(int status)
105 {
106   if(status != 0)
107     fprintf(stderr, _("Try `%s --help\' for more information.\n"), program_name);
108   else
109     {
110       printf(_("Usage: %s [option]...\n\n"), program_name);
111       printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
112                "  -D, --no-detach            Don't fork and detach.\n"
113                "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
114                "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
115                "  -n, --net=NETNAME          Connect to net NETNAME.\n"));
116       printf(_("  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
117                "      --help                 Display this help and exit.\n"
118                "      --version              Output version information and exit.\n\n"));
119       printf(_("Report bugs to tinc@nl.linux.org.\n"));
120     }
121   exit(status);
122 }
123
124 void
125 parse_options(int argc, char **argv, char **envp)
126 {
127   int r;
128   int option_index = 0;
129
130   while((r = getopt_long(argc, argv, "c:Dd::k::n:K::", long_options, &option_index)) != EOF)
131     {
132       switch(r)
133         {
134         case 0: /* long option */
135           break;
136         case 'c': /* config file */
137           confbase = xmalloc(strlen(optarg)+1);
138           strcpy(confbase, optarg);
139           break;
140         case 'D': /* no detach */
141           do_detach = 0;
142           break;
143         case 'd': /* inc debug level */
144           if(optarg)
145             debug_lvl = atoi(optarg);
146           else
147             debug_lvl++;
148           break;
149         case 'k': /* kill old tincds */
150           if(optarg)
151             {
152               if(!strcasecmp(optarg, "HUP"))
153                 kill_tincd = SIGHUP;
154               else if(!strcasecmp(optarg, "TERM"))
155                 kill_tincd = SIGTERM;
156               else if(!strcasecmp(optarg, "KILL"))
157                 kill_tincd = SIGKILL;
158               else if(!strcasecmp(optarg, "USR1"))
159                 kill_tincd = SIGUSR1;
160               else if(!strcasecmp(optarg, "USR2"))
161                 kill_tincd = SIGUSR2;
162               else if(!strcasecmp(optarg, "WINCH"))
163                 kill_tincd = SIGWINCH;
164               else if(!strcasecmp(optarg, "INT"))
165                 kill_tincd = SIGINT;
166               else if(!strcasecmp(optarg, "ALRM"))
167                 kill_tincd = SIGALRM;
168               else
169                 {
170                   kill_tincd = atoi(optarg);
171                   if(!kill_tincd)
172                     {
173                       fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"), optarg);
174                       usage(1);
175                     }
176                 }
177             }
178           else
179             kill_tincd = SIGTERM;
180           break;
181         case 'n': /* net name given */
182           netname = xmalloc(strlen(optarg)+1);
183           strcpy(netname, optarg);
184           break;
185         case 'K': /* generate public/private keypair */
186           if(optarg)
187             {
188               generate_keys = atoi(optarg);
189               if(generate_keys < 512)
190                 {
191                   fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
192                           optarg);
193                   usage(1);
194                 }
195               generate_keys &= ~7;      /* Round it to bytes */
196             }
197           else
198             generate_keys = 1024;
199           break;
200         case '?':
201           usage(1);
202         default:
203           break;
204         }
205     }
206 }
207
208 /* This function prettyprints the key generation process */
209
210 void indicator(int a, int b, void *p)
211 {
212   switch(a)
213   {
214     case 0:
215       fprintf(stderr, ".");
216       break;
217     case 1:
218       fprintf(stderr, "+");
219       break;
220     case 2:
221       fprintf(stderr, "-");
222       break;
223     case 3:
224       switch(b)
225         {
226           case 0:
227             fprintf(stderr, " p\n");
228             break;
229           case 1:
230             fprintf(stderr, " q\n");
231             break;
232           default:
233             fprintf(stderr, "?");
234          }
235        break;
236     default:
237       fprintf(stderr, "?");
238   }
239 }
240
241 #ifdef USE_OPENSSL
242 /*
243   Generate a public/private RSA keypair, and ask for a file to store
244   them in.
245 */
246 int keygen(int bits)
247 {
248   RSA *rsa_key;
249   FILE *f;
250   char *name = NULL;
251   char *filename;
252
253   fprintf(stderr, _("Generating %d bits keys:\n"), bits);
254   rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
255
256   if(!rsa_key)
257     {
258       fprintf(stderr, _("Error during key generation!\n"));
259       return -1;
260     }
261   else
262     fprintf(stderr, _("Done.\n"));
263
264   get_config_string(lookup_config(config_tree, "Name"), &name);
265
266   if(name)
267     asprintf(&filename, "%s/hosts/%s", confbase, name);
268   else
269     asprintf(&filename, "%s/rsa_key.pub", confbase);
270
271   if((f = ask_and_safe_open(filename, _("public RSA key"), "a")) == NULL)
272     return -1;
273
274   if(ftell(f))
275     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
276
277   PEM_write_RSAPublicKey(f, rsa_key);
278   fclose(f);
279   free(filename);
280
281   asprintf(&filename, "%s/rsa_key.priv", confbase);
282   if((f = ask_and_safe_open(filename, _("private RSA key"), "a")) == NULL)
283     return -1;
284
285   if(ftell(f))
286     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
287
288   PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
289   fclose(f);
290   free(filename);
291
292   return 0;
293 }
294 #endif
295
296 /*
297   Set all files and paths according to netname
298 */
299 void make_names(void)
300 {
301   if(netname)
302     {
303       if(!pidfilename)
304         asprintf(&pidfilename, LOCALSTATEDIR "/run/tinc.%s.pid", netname);
305       if(!confbase)
306         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
307       else
308         log(0, TLOG_INFO, _("Both netname and configuration directory given, using the latter..."));
309       if(!identname)
310         asprintf(&identname, "tinc.%s", netname);
311     }
312   else
313     {
314       if(!pidfilename)
315         pidfilename = LOCALSTATEDIR "/run/tinc.pid";
316       if(!confbase)
317         asprintf(&confbase, "%s/tinc", CONFDIR);
318       if(!identname)
319         identname = "tinc";
320     }
321 }
322
323 int
324 main(int argc, char **argv, char **envp)
325 {
326   program_name = argv[0];
327
328   setlocale (LC_ALL, "");
329   bindtextdomain (PACKAGE, LOCALEDIR);
330   textdomain (PACKAGE);
331
332   environment = envp;
333   parse_options(argc, argv, envp);
334
335   if(show_version)
336     {
337       printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE, VERSION, __DATE__, __TIME__, PROT_CURRENT);
338       printf(_("Copyright (C) 1998-2002 Ivo Timmermans, Guus Sliepen and others.\n"
339                "See the AUTHORS file for a complete list.\n\n"
340                "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
341                "and you are welcome to redistribute it under certain conditions;\n"
342                "see the file COPYING for details.\n"));
343
344       return 0;
345     }
346
347   if(show_help)
348     usage(0);
349
350   log_add_hook(log_default);
351
352   g_argv = argv;
353
354   make_names();
355   init_configuration(&config_tree);
356
357   /* Slllluuuuuuurrrrp! */
358 cp
359 #ifdef USE_OPENSSL
360   RAND_load_file("/dev/urandom", 1024);
361
362 #ifdef HAVE_SSLEAY_ADD_ALL_ALGORITHMS
363   SSLeay_add_all_algorithms();
364 #else
365   OpenSSL_add_all_algorithms();
366 #endif
367
368 cp
369   if(generate_keys)
370     {
371       read_server_config();
372       exit(keygen(generate_keys));
373     }
374 #endif
375
376   if(kill_tincd)
377     exit(kill_other(kill_tincd));
378
379   if(read_server_config())
380     exit(1);
381 cp
382   if(detach())
383     exit(0);
384
385   init_callbacks();
386 cp
387   for(;;)
388     {
389       if(!setup_network_connections())
390         {
391           main_loop();
392           cleanup_and_exit(1);
393         }
394
395       log(0, TLOG_ERROR, _("Unrecoverable error"));
396       cp_trace();
397
398       if(do_detach)
399         {
400           log(0, TLOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
401           sleep(maxtimeout);
402         }
403       else
404         {
405           log(0, TLOG_ERROR, _("Not restarting."));
406           exit(1);
407         }
408     }
409 }