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