A reachable node is always more preferable to an unreachable one...
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2002 Ivo Timmermans <ivo@o2w.nl>
4                   2000-2002 Guus Sliepen <guus@sliepen.eu.org>
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.61 2002/07/16 13:12:49 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 #include <sys/mman.h>
37
38 #ifdef HAVE_SYS_IOCTL_H
39 # include <sys/ioctl.h>
40 #endif
41
42 #include <openssl/rand.h>
43 #include <openssl/rsa.h>
44 #include <openssl/pem.h>
45 #include <openssl/evp.h>
46
47 #include <utils.h>
48 #include <xalloc.h>
49
50 #include "conf.h"
51 #include "net.h"
52 #include "netutl.h"
53 #include "process.h"
54 #include "protocol.h"
55 #include "subnet.h"
56
57 #include "system.h"
58
59 /* The name this program was run with. */
60 char *program_name;
61
62 /* If nonzero, display usage information and exit. */
63 int show_help;
64
65 /* If nonzero, print the version on standard output and exit.  */
66 int show_version;
67
68 /* If nonzero, it will attempt to kill a running tincd and exit. */
69 int kill_tincd = 0;
70
71 /* If nonzero, generate public/private keypair for this host/net. */
72 int generate_keys = 0;
73
74 /* If nonzero, use null ciphers and skip all key exchanges. */
75 int bypass_security = 0;
76
77 /* If nonzero, disable swapping for this process. */
78 int do_mlock = 0;
79
80 char *identname;                 /* program name for syslog */
81 char *pidfilename;               /* pid file location */
82 char **g_argv;                   /* a copy of the cmdline arguments */
83 char **environment;              /* A pointer to the environment on
84                                     startup */
85
86 static struct option const long_options[] =
87 {
88   { "config", required_argument, NULL, 'c' },
89   { "kill", optional_argument, NULL, 'k' },
90   { "net", required_argument, NULL, 'n' },
91   { "help", no_argument, &show_help, 1 },
92   { "version", no_argument, &show_version, 1 },
93   { "no-detach", no_argument, &do_detach, 0 },
94   { "generate-keys", optional_argument, NULL, 'K'},
95   { "debug", optional_argument, NULL, 'd'},
96   { "bypass-security", no_argument, &bypass_security, 1 },
97   { "mlock", no_argument, &do_mlock, 1},
98   { NULL, 0, NULL, 0 }
99 };
100
101 static void
102 usage(int status)
103 {
104   if(status != 0)
105     fprintf(stderr, _("Try `%s --help\' for more information.\n"), program_name);
106   else
107     {
108       printf(_("Usage: %s [option]...\n\n"), program_name);
109       printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
110                "  -D, --no-detach            Don't fork and detach.\n"
111                "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
112                "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
113                "  -n, --net=NETNAME          Connect to net NETNAME.\n"
114                "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
115                "  -L, --mlock                Lock tinc into main memory.\n"
116                "      --help                 Display this help and exit.\n"
117                "      --version              Output version information and exit.\n\n"));
118       printf(_("Report bugs to tinc@nl.linux.org.\n"));
119     }
120   exit(status);
121 }
122
123 void
124 parse_options(int argc, char **argv, char **envp)
125 {
126   int r;
127   int option_index = 0;
128
129   while((r = getopt_long(argc, argv, "c:DLd::k::n:K::", long_options, &option_index)) != EOF)
130     {
131       switch(r)
132         {
133         case 0: /* long option */
134           break;
135         case 'c': /* config file */
136           confbase = xmalloc(strlen(optarg)+1);
137           strcpy(confbase, optarg);
138           break;
139         case 'D': /* no detach */
140           do_detach = 0;
141           break;
142         case 'L': /* no detach */
143           do_mlock = 1;
144           break;
145         case 'd': /* inc debug level */
146           if(optarg)
147             debug_lvl = atoi(optarg);
148           else
149             debug_lvl++;
150           break;
151         case 'k': /* kill old tincds */
152           if(optarg)
153             {
154               if(!strcasecmp(optarg, "HUP"))
155                 kill_tincd = SIGHUP;
156               else if(!strcasecmp(optarg, "TERM"))
157                 kill_tincd = SIGTERM;
158               else if(!strcasecmp(optarg, "KILL"))
159                 kill_tincd = SIGKILL;
160               else if(!strcasecmp(optarg, "USR1"))
161                 kill_tincd = SIGUSR1;
162               else if(!strcasecmp(optarg, "USR2"))
163                 kill_tincd = SIGUSR2;
164               else if(!strcasecmp(optarg, "WINCH"))
165                 kill_tincd = SIGWINCH;
166               else if(!strcasecmp(optarg, "INT"))
167                 kill_tincd = SIGINT;
168               else if(!strcasecmp(optarg, "ALRM"))
169                 kill_tincd = SIGALRM;
170               else
171                 {
172                   kill_tincd = atoi(optarg);
173                   if(!kill_tincd)
174                     {
175                       fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"), optarg);
176                       usage(1);
177                     }
178                 }
179             }
180           else
181             kill_tincd = SIGTERM;
182           break;
183         case 'n': /* net name given */
184           netname = xmalloc(strlen(optarg)+1);
185           strcpy(netname, optarg);
186           break;
187         case 'K': /* generate public/private keypair */
188           if(optarg)
189             {
190               generate_keys = atoi(optarg);
191               if(generate_keys < 512)
192                 {
193                   fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
194                           optarg);
195                   usage(1);
196                 }
197               generate_keys &= ~7;      /* Round it to bytes */
198             }
199           else
200             generate_keys = 1024;
201           break;
202         case '?':
203           usage(1);
204         default:
205           break;
206         }
207     }
208 }
209
210 /* This function prettyprints the key generation process */
211
212 void indicator(int a, int b, void *p)
213 {
214   switch(a)
215   {
216     case 0:
217       fprintf(stderr, ".");
218       break;
219     case 1:
220       fprintf(stderr, "+");
221       break;
222     case 2:
223       fprintf(stderr, "-");
224       break;
225     case 3:
226       switch(b)
227         {
228           case 0:
229             fprintf(stderr, " p\n");
230             break;
231           case 1:
232             fprintf(stderr, " q\n");
233             break;
234           default:
235             fprintf(stderr, "?");
236          }
237        break;
238     default:
239       fprintf(stderr, "?");
240   }
241 }
242
243 /*
244   Generate a public/private RSA keypair, and ask for a file to store
245   them in.
246 */
247 int keygen(int bits)
248 {
249   RSA *rsa_key;
250   FILE *f;
251   char *name = NULL;
252   char *filename;
253
254   fprintf(stderr, _("Generating %d bits keys:\n"), bits);
255   rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
256
257   if(!rsa_key)
258     {
259       fprintf(stderr, _("Error during key generation!\n"));
260       return -1;
261     }
262   else
263     fprintf(stderr, _("Done.\n"));
264
265   get_config_string(lookup_config(config_tree, "Name"), &name);
266
267   if(name)
268     asprintf(&filename, "%s/hosts/%s", confbase, name);
269   else
270     asprintf(&filename, "%s/rsa_key.pub", confbase);
271
272   if((f = ask_and_safe_open(filename, _("public RSA key"), "a")) == NULL)
273     return -1;
274
275   if(ftell(f))
276     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
277
278   PEM_write_RSAPublicKey(f, rsa_key);
279   fclose(f);
280   free(filename);
281
282   asprintf(&filename, "%s/rsa_key.priv", confbase);
283   if((f = ask_and_safe_open(filename, _("private RSA key"), "a")) == NULL)
284     return -1;
285
286   if(ftell(f))
287     fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
288
289   PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
290   fclose(f);
291   free(filename);
292
293   return 0;
294 }
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         syslog(LOG_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 #ifndef LOG_PERROR
351   openlog("tinc", LOG_CONS, LOG_DAEMON);        /* Catch all syslog() calls issued before detaching */
352 #else
353   openlog("tinc", LOG_PERROR, LOG_DAEMON);      /* Catch all syslog() calls issued before detaching */
354 #endif
355
356   /* Lock all pages into memory if requested */
357   
358   if(do_mlock)
359     if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
360       syslog(LOG_ERR, _("System call `%s' failed: %s"), "mlockall", strerror(errno));
361       return -1;
362     }
363   
364   g_argv = argv;
365
366   make_names();
367   init_configuration(&config_tree);
368
369   /* Slllluuuuuuurrrrp! */
370 cp
371   RAND_load_file("/dev/urandom", 1024);
372
373 #ifdef HAVE_SSLEAY_ADD_ALL_ALGORITHMS
374   SSLeay_add_all_algorithms();
375 #else
376   OpenSSL_add_all_algorithms();
377 #endif
378
379 cp
380   if(generate_keys)
381     {
382       read_server_config();
383       exit(keygen(generate_keys));
384     }
385
386   if(kill_tincd)
387     exit(kill_other(kill_tincd));
388
389   if(read_server_config())
390     exit(1);
391 cp
392   if(detach())
393     exit(0);
394 cp
395   for(;;)
396     {
397       if(!setup_network_connections())
398         {
399           main_loop();
400           cleanup_and_exit(1);
401         }
402
403       syslog(LOG_ERR, _("Unrecoverable error"));
404       cp_trace();
405
406       if(do_detach)
407         {
408           syslog(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
409           sleep(maxtimeout);
410         }
411       else
412         {
413           syslog(LOG_ERR, _("Not restarting."));
414           exit(1);
415         }
416     }
417 }