MacOS/X needs #define _P1003_1B_VISIBLE in order to use mlockall().
[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.64 2002/09/15 12:26:04 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(_
114                            ("  -c, --config=DIR           Read configuration options from DIR.\n"
115                                 "  -D, --no-detach            Don't fork and detach.\n"
116                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
117                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
118                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
119                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
120                                 "  -L, --mlock                Lock tinc into main memory.\n"
121                                 "      --help                 Display this help and exit.\n"
122                                 "      --version              Output version information and exit.\n\n"));
123                 printf(_("Report bugs to tinc@nl.linux.org.\n"));
124         }
125
126         exit(status);
127 }
128
129 void parse_options(int argc, char **argv, char **envp)
130 {
131         int r;
132         int option_index = 0;
133
134         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::", long_options, &option_index)) != EOF) {
135                 switch (r) {
136                         case 0:                         /* long option */
137                                 break;
138
139                         case 'c':                               /* config file */
140                                 confbase = xmalloc(strlen(optarg) + 1);
141                                 strcpy(confbase, optarg);
142                                 break;
143
144                         case 'D':                               /* no detach */
145                                 do_detach = 0;
146                                 break;
147
148                         case 'L':                               /* no detach */
149                                 do_mlock = 1;
150                                 break;
151
152                         case 'd':                               /* inc debug level */
153                                 if(optarg)
154                                         debug_lvl = atoi(optarg);
155                                 else
156                                         debug_lvl++;
157                                 break;
158
159                         case 'k':                               /* kill old tincds */
160                                 if(optarg) {
161                                         if(!strcasecmp(optarg, "HUP"))
162                                                 kill_tincd = SIGHUP;
163                                         else if(!strcasecmp(optarg, "TERM"))
164                                                 kill_tincd = SIGTERM;
165                                         else if(!strcasecmp(optarg, "KILL"))
166                                                 kill_tincd = SIGKILL;
167                                         else if(!strcasecmp(optarg, "USR1"))
168                                                 kill_tincd = SIGUSR1;
169                                         else if(!strcasecmp(optarg, "USR2"))
170                                                 kill_tincd = SIGUSR2;
171                                         else if(!strcasecmp(optarg, "WINCH"))
172                                                 kill_tincd = SIGWINCH;
173                                         else if(!strcasecmp(optarg, "INT"))
174                                                 kill_tincd = SIGINT;
175                                         else if(!strcasecmp(optarg, "ALRM"))
176                                                 kill_tincd = SIGALRM;
177                                         else {
178                                                 kill_tincd = atoi(optarg);
179
180                                                 if(!kill_tincd) {
181                                                         fprintf(stderr,
182                                                                         _
183                                                                         ("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
184                                                                         optarg);
185                                                         usage(1);
186                                                 }
187                                         }
188                                 } else
189                                         kill_tincd = SIGTERM;
190                                 break;
191
192                         case 'n':                               /* net name given */
193                                 netname = xmalloc(strlen(optarg) + 1);
194                                 strcpy(netname, optarg);
195                                 break;
196
197                         case 'K':                               /* generate public/private keypair */
198                                 if(optarg) {
199                                         generate_keys = atoi(optarg);
200
201                                         if(generate_keys < 512) {
202                                                 fprintf(stderr,
203                                                                 _
204                                                                 ("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
205                                                                 optarg);
206                                                 usage(1);
207                                         }
208
209                                         generate_keys &= ~7;    /* Round it to bytes */
210                                 } else
211                                         generate_keys = 1024;
212                                 break;
213
214                         case '?':
215                                 usage(1);
216
217                         default:
218                                 break;
219                 }
220         }
221 }
222
223 /* This function prettyprints the key generation process */
224
225 void indicator(int a, int b, void *p)
226 {
227         switch (a) {
228                 case 0:
229                         fprintf(stderr, ".");
230                         break;
231
232                 case 1:
233                         fprintf(stderr, "+");
234                         break;
235
236                 case 2:
237                         fprintf(stderr, "-");
238                         break;
239
240                 case 3:
241                         switch (b) {
242                                 case 0:
243                                         fprintf(stderr, " p\n");
244                                         break;
245
246                                 case 1:
247                                         fprintf(stderr, " q\n");
248                                         break;
249
250                                 default:
251                                         fprintf(stderr, "?");
252                         }
253                         break;
254
255                 default:
256                         fprintf(stderr, "?");
257         }
258 }
259
260 /*
261   Generate a public/private RSA keypair, and ask for a file to store
262   them in.
263 */
264 int keygen(int bits)
265 {
266         RSA *rsa_key;
267         FILE *f;
268         char *name = NULL;
269         char *filename;
270
271         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
272         rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
273
274         if(!rsa_key) {
275                 fprintf(stderr, _("Error during key generation!\n"));
276                 return -1;
277         } else
278                 fprintf(stderr, _("Done.\n"));
279
280         get_config_string(lookup_config(config_tree, "Name"), &name);
281
282         if(name)
283                 asprintf(&filename, "%s/hosts/%s", confbase, name);
284         else
285                 asprintf(&filename, "%s/rsa_key.pub", confbase);
286
287         f = ask_and_safe_open(filename, _("public RSA key"), "a");
288
289         if(!f)
290                 return -1;
291
292         if(ftell(f))
293                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
294
295         PEM_write_RSAPublicKey(f, rsa_key);
296         fclose(f);
297         free(filename);
298
299         asprintf(&filename, "%s/rsa_key.priv", confbase);
300         f = ask_and_safe_open(filename, _("private RSA key"), "a");
301
302         if(!f)
303                 return -1;
304
305         if(ftell(f))
306                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
307
308         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
309         fclose(f);
310         free(filename);
311
312         return 0;
313 }
314
315 /*
316   Set all files and paths according to netname
317 */
318 void make_names(void)
319 {
320         if(netname) {
321                 if(!pidfilename)
322                         asprintf(&pidfilename, LOCALSTATEDIR "/run/tinc.%s.pid", netname);
323
324                 if(!confbase)
325                         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
326                 else
327                         syslog(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
328
329                 if(!identname)
330                         asprintf(&identname, "tinc.%s", netname);
331         } else {
332                 if(!pidfilename)
333                         pidfilename = LOCALSTATEDIR "/run/tinc.pid";
334
335                 if(!confbase)
336                         asprintf(&confbase, "%s/tinc", CONFDIR);
337
338                 if(!identname)
339                         identname = "tinc";
340         }
341 }
342
343 int main(int argc, char **argv, char **envp)
344 {
345         program_name = argv[0];
346
347         setlocale(LC_ALL, "");
348         bindtextdomain(PACKAGE, LOCALEDIR);
349         textdomain(PACKAGE);
350
351         environment = envp;
352         parse_options(argc, argv, envp);
353
354         if(show_version) {
355                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
356                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
357                 printf(_("Copyright (C) 1998-2002 Ivo Timmermans, Guus Sliepen and others.\n"
358                                 "See the AUTHORS file for a complete list.\n\n"
359                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
360                                 "and you are welcome to redistribute it under certain conditions;\n"
361                                 "see the file COPYING for details.\n"));
362
363                 return 0;
364         }
365
366         if(show_help)
367                 usage(0);
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_SSLEAY_ADD_ALL_ALGORITHMS
399         SSLeay_add_all_algorithms();
400 #else
401         OpenSSL_add_all_algorithms();
402 #endif
403
404         if(generate_keys) {
405                 read_server_config();
406                 exit(keygen(generate_keys));
407         }
408
409         if(kill_tincd)
410                 exit(kill_other(kill_tincd));
411
412         if(read_server_config())
413                 exit(1);
414
415         if(detach())
416                 exit(0);
417
418         for(;;) {
419                 if(!setup_network_connections()) {
420                         main_loop();
421                         cleanup_and_exit(1);
422                 }
423
424                 syslog(LOG_ERR, _("Unrecoverable error"));
425                 cp_trace();
426
427                 if(do_detach) {
428                         syslog(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
429                         sleep(maxtimeout);
430                 } else {
431                         syslog(LOG_ERR, _("Not restarting."));
432                         exit(1);
433                 }
434         }
435 }