Small fixes to make LZO compression work.
[oweals/tinc.git] / 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.67 2003/05/06 23:14:45 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 /* Darwin (MacOS/X) needs the following definition... */
38 #ifndef _P1003_1B_VISIBLE
39 #define _P1003_1B_VISIBLE
40 #endif
41
42 #include <sys/mman.h>
43
44 #ifdef HAVE_SYS_IOCTL_H
45 # include <sys/ioctl.h>
46 #endif
47
48 #include <openssl/rand.h>
49 #include <openssl/rsa.h>
50 #include <openssl/pem.h>
51 #include <openssl/evp.h>
52
53 #include <lzo1x.h>
54
55 #include <utils.h>
56 #include <xalloc.h>
57
58 #include "conf.h"
59 #include "net.h"
60 #include "netutl.h"
61 #include "process.h"
62 #include "protocol.h"
63 #include "subnet.h"
64
65 #include "system.h"
66
67 /* The name this program was run with. */
68 char *program_name;
69
70 /* If nonzero, display usage information and exit. */
71 int show_help;
72
73 /* If nonzero, print the version on standard output and exit.  */
74 int show_version;
75
76 /* If nonzero, it will attempt to kill a running tincd and exit. */
77 int kill_tincd = 0;
78
79 /* If nonzero, generate public/private keypair for this host/net. */
80 int generate_keys = 0;
81
82 /* If nonzero, use null ciphers and skip all key exchanges. */
83 int bypass_security = 0;
84
85 /* If nonzero, disable swapping for this process. */
86 int do_mlock = 0;
87
88 char *identname;                                /* program name for syslog */
89 char *pidfilename;                              /* pid file location */
90 char **g_argv;                                  /* a copy of the cmdline arguments */
91 char **environment;                             /* A pointer to the environment on
92                                                                    startup */
93
94 static struct option const long_options[] = {
95         {"config", required_argument, NULL, 'c'},
96         {"kill", optional_argument, NULL, 'k'},
97         {"net", required_argument, NULL, 'n'},
98         {"help", no_argument, &show_help, 1},
99         {"version", no_argument, &show_version, 1},
100         {"no-detach", no_argument, &do_detach, 0},
101         {"generate-keys", optional_argument, NULL, 'K'},
102         {"debug", optional_argument, NULL, 'd'},
103         {"bypass-security", no_argument, &bypass_security, 1},
104         {"mlock", no_argument, &do_mlock, 1},
105         {NULL, 0, NULL, 0}
106 };
107
108 static void usage(int status)
109 {
110         if(status != 0)
111                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
112                                 program_name);
113         else {
114                 printf(_("Usage: %s [option]...\n\n"), program_name);
115                 printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
116                                 "  -D, --no-detach            Don't fork and detach.\n"
117                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
118                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
119                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
120                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
121                                 "  -L, --mlock                Lock tinc into main memory.\n"
122                                 "      --help                 Display this help and exit.\n"
123                                 "      --version              Output version information and exit.\n\n"));
124                 printf(_("Report bugs to tinc@nl.linux.org.\n"));
125         }
126
127         exit(status);
128 }
129
130 void parse_options(int argc, char **argv, char **envp)
131 {
132         int r;
133         int option_index = 0;
134
135         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::", long_options, &option_index)) != EOF) {
136                 switch (r) {
137                         case 0:                         /* long option */
138                                 break;
139
140                         case 'c':                               /* config file */
141                                 confbase = xmalloc(strlen(optarg) + 1);
142                                 strcpy(confbase, optarg);
143                                 break;
144
145                         case 'D':                               /* no detach */
146                                 do_detach = 0;
147                                 break;
148
149                         case 'L':                               /* no detach */
150                                 do_mlock = 1;
151                                 break;
152
153                         case 'd':                               /* inc debug level */
154                                 if(optarg)
155                                         debug_lvl = atoi(optarg);
156                                 else
157                                         debug_lvl++;
158                                 break;
159
160                         case 'k':                               /* kill old tincds */
161                                 if(optarg) {
162                                         if(!strcasecmp(optarg, "HUP"))
163                                                 kill_tincd = SIGHUP;
164                                         else if(!strcasecmp(optarg, "TERM"))
165                                                 kill_tincd = SIGTERM;
166                                         else if(!strcasecmp(optarg, "KILL"))
167                                                 kill_tincd = SIGKILL;
168                                         else if(!strcasecmp(optarg, "USR1"))
169                                                 kill_tincd = SIGUSR1;
170                                         else if(!strcasecmp(optarg, "USR2"))
171                                                 kill_tincd = SIGUSR2;
172                                         else if(!strcasecmp(optarg, "WINCH"))
173                                                 kill_tincd = SIGWINCH;
174                                         else if(!strcasecmp(optarg, "INT"))
175                                                 kill_tincd = SIGINT;
176                                         else if(!strcasecmp(optarg, "ALRM"))
177                                                 kill_tincd = SIGALRM;
178                                         else {
179                                                 kill_tincd = atoi(optarg);
180
181                                                 if(!kill_tincd) {
182                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
183                                                                         optarg);
184                                                         usage(1);
185                                                 }
186                                         }
187                                 } else
188                                         kill_tincd = SIGTERM;
189                                 break;
190
191                         case 'n':                               /* net name given */
192                                 netname = xmalloc(strlen(optarg) + 1);
193                                 strcpy(netname, optarg);
194                                 break;
195
196                         case 'K':                               /* generate public/private keypair */
197                                 if(optarg) {
198                                         generate_keys = atoi(optarg);
199
200                                         if(generate_keys < 512) {
201                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
202                                                                 optarg);
203                                                 usage(1);
204                                         }
205
206                                         generate_keys &= ~7;    /* Round it to bytes */
207                                 } else
208                                         generate_keys = 1024;
209                                 break;
210
211                         case '?':
212                                 usage(1);
213
214                         default:
215                                 break;
216                 }
217         }
218 }
219
220 /* This function prettyprints the key generation process */
221
222 void indicator(int a, int b, void *p)
223 {
224         switch (a) {
225                 case 0:
226                         fprintf(stderr, ".");
227                         break;
228
229                 case 1:
230                         fprintf(stderr, "+");
231                         break;
232
233                 case 2:
234                         fprintf(stderr, "-");
235                         break;
236
237                 case 3:
238                         switch (b) {
239                                 case 0:
240                                         fprintf(stderr, " p\n");
241                                         break;
242
243                                 case 1:
244                                         fprintf(stderr, " q\n");
245                                         break;
246
247                                 default:
248                                         fprintf(stderr, "?");
249                         }
250                         break;
251
252                 default:
253                         fprintf(stderr, "?");
254         }
255 }
256
257 /*
258   Generate a public/private RSA keypair, and ask for a file to store
259   them in.
260 */
261 int keygen(int bits)
262 {
263         RSA *rsa_key;
264         FILE *f;
265         char *name = NULL;
266         char *filename;
267
268         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
269         rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
270
271         if(!rsa_key) {
272                 fprintf(stderr, _("Error during key generation!\n"));
273                 return -1;
274         } else
275                 fprintf(stderr, _("Done.\n"));
276
277         get_config_string(lookup_config(config_tree, "Name"), &name);
278
279         if(name)
280                 asprintf(&filename, "%s/hosts/%s", confbase, name);
281         else
282                 asprintf(&filename, "%s/rsa_key.pub", confbase);
283
284         f = ask_and_safe_open(filename, _("public RSA key"), "a");
285
286         if(!f)
287                 return -1;
288
289         if(ftell(f))
290                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
291
292         PEM_write_RSAPublicKey(f, rsa_key);
293         fclose(f);
294         free(filename);
295
296         asprintf(&filename, "%s/rsa_key.priv", confbase);
297         f = ask_and_safe_open(filename, _("private RSA key"), "a");
298
299         if(!f)
300                 return -1;
301
302         if(ftell(f))
303                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
304
305         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
306         fclose(f);
307         free(filename);
308
309         return 0;
310 }
311
312 /*
313   Set all files and paths according to netname
314 */
315 void make_names(void)
316 {
317         if(netname) {
318                 if(!pidfilename)
319                         asprintf(&pidfilename, LOCALSTATEDIR "/run/tinc.%s.pid", netname);
320
321                 if(!confbase)
322                         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
323                 else
324                         syslog(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
325
326                 if(!identname)
327                         asprintf(&identname, "tinc.%s", netname);
328         } else {
329                 if(!pidfilename)
330                         pidfilename = LOCALSTATEDIR "/run/tinc.pid";
331
332                 if(!confbase)
333                         asprintf(&confbase, "%s/tinc", CONFDIR);
334
335                 if(!identname)
336                         identname = "tinc";
337         }
338 }
339
340 int main(int argc, char **argv, char **envp)
341 {
342         program_name = argv[0];
343
344         setlocale(LC_ALL, "");
345         bindtextdomain(PACKAGE, LOCALEDIR);
346         textdomain(PACKAGE);
347
348         environment = envp;
349         parse_options(argc, argv, envp);
350
351         if(show_version) {
352                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
353                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
354                 printf(_("Copyright (C) 1998-2002 Ivo Timmermans, Guus Sliepen and others.\n"
355                                 "See the AUTHORS file for a complete list.\n\n"
356                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
357                                 "and you are welcome to redistribute it under certain conditions;\n"
358                                 "see the file COPYING for details.\n"));
359
360                 return 0;
361         }
362
363         if(show_help)
364                 usage(0);
365
366         if(kill_tincd)
367                 exit(kill_other(kill_tincd));
368
369 #ifndef LOG_PERROR
370         openlog("tinc", LOG_CONS, LOG_DAEMON);  /* Catch all syslog() calls issued before detaching */
371 #else
372         openlog("tinc", LOG_PERROR, LOG_DAEMON);        /* Catch all syslog() calls issued before detaching */
373 #endif
374
375         /* Lock all pages into memory if requested */
376
377         if(do_mlock)
378 #ifdef HAVE_MLOCKALL
379                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
380                         syslog(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
381                                    strerror(errno));
382 #else
383         {
384                 syslog(LOG_ERR, _("mlockall() not supported on this platform!"));
385 #endif
386                 return -1;
387         }
388
389         g_argv = argv;
390
391         make_names();
392         init_configuration(&config_tree);
393
394         /* Slllluuuuuuurrrrp! */
395
396         RAND_load_file("/dev/urandom", 1024);
397
398 #ifdef HAVE_OPENSSL_ADD_ALL_ALGORITHMS_NOCONF
399         OPENSSL_add_all_algorithms_noconf();
400 #else
401 #ifdef HAVE_OPENSSL_ADD_ALL_ALGORITHMS
402         OpenSSL_add_all_algorithms();
403 #else
404 #ifdef HAVE_SSLEAY_ADD_ALL_ALGORITHMS
405         SSLeay_add_all_algorithms();
406 #else
407 #error No add_all_algorithms function available!
408 #endif
409 #endif
410 #endif
411
412         if(generate_keys) {
413                 read_server_config();
414                 exit(keygen(generate_keys));
415         }
416
417         if(read_server_config())
418                 exit(1);
419
420         if(lzo_init() != LZO_E_OK) {
421                 syslog(LOG_ERR, _("Error initializing LZO compressor!"));
422                 exit(1);
423         }
424
425         if(detach())
426                 exit(0);
427                 
428         for(;;) {
429                 if(!setup_network_connections()) {
430                         main_loop();
431                         cleanup_and_exit(1);
432                 }
433
434                 syslog(LOG_ERR, _("Unrecoverable error"));
435                 cp_trace();
436
437                 if(do_detach) {
438                         syslog(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
439                         sleep(maxtimeout);
440                 } else {
441                         syslog(LOG_ERR, _("Not restarting."));
442                         exit(1);
443                 }
444         }
445 }