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