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