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