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