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