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