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