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