Prevent multiple inclusions.
[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.86 2003/08/17 09:03:30 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 <getopt.h>
42
43 #include "conf.h"
44 #include "device.h"
45 #include "logger.h"
46 #include "net.h"
47 #include "netutl.h"
48 #include "process.h"
49 #include "protocol.h"
50 #include "utils.h"
51 #include "xalloc.h"
52
53 /* The name this program was run with. */
54 char *program_name = NULL;
55
56 /* If nonzero, display usage information and exit. */
57 bool show_help = false;
58
59 /* If nonzero, print the version on standard output and exit.  */
60 bool show_version = false;
61
62 /* If nonzero, it will attempt to kill a running tincd and exit. */
63 int kill_tincd = 0;
64
65 /* If nonzero, generate public/private keypair for this host/net. */
66 int generate_keys = 0;
67
68 /* If nonzero, use null ciphers and skip all key exchanges. */
69 bool bypass_security = false;
70
71 /* If nonzero, disable swapping for this process. */
72 bool do_mlock = false;
73
74 /* If nonzero, write log entries to a separate file. */
75 bool use_logfile = false;
76
77 char *identname = NULL;                         /* program name for syslog */
78 char *pidfilename = NULL;                       /* pid file location */
79 char *logfilename = NULL;                       /* log file location */
80 char **g_argv;                                  /* a copy of the cmdline arguments */
81
82 static int status;
83
84 static struct option const long_options[] = {
85         {"config", required_argument, NULL, 'c'},
86         {"kill", optional_argument, NULL, 'k'},
87         {"net", required_argument, NULL, 'n'},
88         {"help", no_argument, NULL, 1},
89         {"version", no_argument, NULL, 2},
90         {"no-detach", no_argument, NULL, 'D'},
91         {"generate-keys", optional_argument, NULL, 'K'},
92         {"debug", optional_argument, NULL, 'd'},
93         {"bypass-security", no_argument, NULL, 3},
94         {"mlock", no_argument, NULL, 'L'},
95         {"logfile", optional_argument, NULL, 4},
96         {"pidfile", required_argument, NULL, 5},
97         {NULL, 0, NULL, 0}
98 };
99
100 #ifdef HAVE_MINGW
101 static struct WSAData wsa_state;
102 #endif
103
104 static void usage(bool status)
105 {
106         if(status)
107                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
108                                 program_name);
109         else {
110                 printf(_("Usage: %s [option]...\n\n"), program_name);
111                 printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
112                                 "  -D, --no-detach            Don't fork and detach.\n"
113                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
114                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
115                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
116                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
117                                 "  -L, --mlock                Lock tinc into main memory.\n"
118                                 "      --logfile[=FILENAME]   Write log entries to a logfile.\n"
119                                 "      --pidfile=FILENAME     Write PID to FILENAME.\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
126 static bool parse_options(int argc, char **argv)
127 {
128         int r;
129         int option_index = 0;
130
131         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::", long_options, &option_index)) != EOF) {
132                 switch (r) {
133                         case 0:                         /* long option */
134                                 break;
135
136                         case 'c':                               /* config file */
137                                 confbase = xstrdup(optarg);
138                                 break;
139
140                         case 'D':                               /* no detach */
141                                 do_detach = false;
142                                 break;
143
144                         case 'L':                               /* no detach */
145                                 do_mlock = true;
146                                 break;
147
148                         case 'd':                               /* inc debug level */
149                                 if(optarg)
150                                         debug_level = atoi(optarg);
151                                 else
152                                         debug_level++;
153                                 break;
154
155                         case 'k':                               /* kill old tincds */
156 #ifndef HAVE_MINGW
157                                 if(optarg) {
158                                         if(!strcasecmp(optarg, "HUP"))
159                                                 kill_tincd = SIGHUP;
160                                         else if(!strcasecmp(optarg, "TERM"))
161                                                 kill_tincd = SIGTERM;
162                                         else if(!strcasecmp(optarg, "KILL"))
163                                                 kill_tincd = SIGKILL;
164                                         else if(!strcasecmp(optarg, "USR1"))
165                                                 kill_tincd = SIGUSR1;
166                                         else if(!strcasecmp(optarg, "USR2"))
167                                                 kill_tincd = SIGUSR2;
168                                         else if(!strcasecmp(optarg, "WINCH"))
169                                                 kill_tincd = SIGWINCH;
170                                         else if(!strcasecmp(optarg, "INT"))
171                                                 kill_tincd = SIGINT;
172                                         else if(!strcasecmp(optarg, "ALRM"))
173                                                 kill_tincd = SIGALRM;
174                                         else {
175                                                 kill_tincd = atoi(optarg);
176
177                                                 if(!kill_tincd) {
178                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
179                                                                         optarg);
180                                                         usage(true);
181                                                         return false;
182                                                 }
183                                         }
184                                 } else
185                                         kill_tincd = SIGTERM;
186 #else
187                                         kill_tincd = 1;
188 #endif
189                                 break;
190
191                         case 'n':                               /* net name given */
192                                 netname = xstrdup(optarg);
193                                 break;
194
195                         case 'K':                               /* generate public/private keypair */
196                                 if(optarg) {
197                                         generate_keys = atoi(optarg);
198
199                                         if(generate_keys < 512) {
200                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
201                                                                 optarg);
202                                                 usage(true);
203                                                 return false;
204                                         }
205
206                                         generate_keys &= ~7;    /* Round it to bytes */
207                                 } else
208                                         generate_keys = 1024;
209                                 break;
210
211                         case 1:                                 /* show help */
212                                 show_help = true;
213                                 break;
214
215                         case 2:                                 /* show version */
216                                 show_version = true;
217                                 break;
218
219                         case 3:                                 /* bypass security */
220                                 bypass_security = true;
221                                 break;
222
223                         case 4:                                 /* write log entries to a file */
224                                 use_logfile = true;
225                                 if(optarg)
226                                         logfilename = xstrdup(optarg);
227                                 break;
228
229                         case 5:                                 /* write PID to a file */
230                                 pidfilename = xstrdup(optarg);
231                                 break;
232
233                         case '?':
234                                 usage(true);
235                                 return false;
236
237                         default:
238                                 break;
239                 }
240         }
241
242         return true;
243 }
244
245 /* This function prettyprints the key generation process */
246
247 static void indicator(int a, int b, void *p)
248 {
249         switch (a) {
250                 case 0:
251                         fprintf(stderr, ".");
252                         break;
253
254                 case 1:
255                         fprintf(stderr, "+");
256                         break;
257
258                 case 2:
259                         fprintf(stderr, "-");
260                         break;
261
262                 case 3:
263                         switch (b) {
264                                 case 0:
265                                         fprintf(stderr, " p\n");
266                                         break;
267
268                                 case 1:
269                                         fprintf(stderr, " q\n");
270                                         break;
271
272                                 default:
273                                         fprintf(stderr, "?");
274                         }
275                         break;
276
277                 default:
278                         fprintf(stderr, "?");
279         }
280 }
281
282 /*
283   Generate a public/private RSA keypair, and ask for a file to store
284   them in.
285 */
286 static bool keygen(int bits)
287 {
288         RSA *rsa_key;
289         FILE *f;
290         char *name = NULL;
291         char *filename;
292
293         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
294         rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
295
296         if(!rsa_key) {
297                 fprintf(stderr, _("Error during key generation!\n"));
298                 return false;
299         } else
300                 fprintf(stderr, _("Done.\n"));
301
302         asprintf(&filename, "%s/rsa_key.priv", confbase);
303         f = ask_and_open(filename, _("private RSA key"), "a");
304
305         if(!f)
306                 return false;
307   
308 #ifdef HAVE_FCHMOD
309         /* Make it unreadable for others. */
310         fchmod(fileno(f), 0600);
311 #endif
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         get_config_string(lookup_config(config_tree, "Name"), &name);
321
322         if(name)
323                 asprintf(&filename, "%s/hosts/%s", confbase, name);
324         else
325                 asprintf(&filename, "%s/rsa_key.pub", confbase);
326
327         f = ask_and_open(filename, _("public RSA key"), "a");
328
329         if(!f)
330                 return false;
331
332         if(ftell(f))
333                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
334
335         PEM_write_RSAPublicKey(f, rsa_key);
336         fclose(f);
337         free(filename);
338
339         return true;
340 }
341
342 /*
343   Set all files and paths according to netname
344 */
345 static void make_names(void)
346 {
347 #ifdef HAVE_MINGW
348         HKEY key;
349         char installdir[1024] = "";
350         long len = sizeof(installdir);
351 #endif
352
353         if(netname)
354                 asprintf(&identname, "tinc.%s", netname);
355         else
356                 identname = xstrdup("tinc");
357
358 #ifdef HAVE_MINGW
359         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
360                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
361                         if(!logfilename)
362                                 asprintf(&logfilename, "%s/log/%s.log", identname);
363                         if(!confbase) {
364                                 if(netname)
365                                         asprintf(&confbase, "%s/%s", installdir, netname);
366                                 else
367                                         asprintf(&confbase, "%s", installdir);
368                         }
369                 }
370                 RegCloseKey(key);
371                 if(*installdir)
372                         return;
373         }
374 #endif
375
376         if(!pidfilename)
377                 asprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
378
379         if(!logfilename)
380                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
381
382         if(netname) {
383                 if(!confbase)
384                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
385                 else
386                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
387         } else {
388                 if(!confbase)
389                         asprintf(&confbase, CONFDIR "/tinc");
390         }
391 }
392
393 int main(int argc, char **argv)
394 {
395         program_name = argv[0];
396
397         setlocale(LC_ALL, "");
398         bindtextdomain(PACKAGE, LOCALEDIR);
399         textdomain(PACKAGE);
400
401         if(!parse_options(argc, argv))
402                 return 1;
403         
404         make_names();
405
406         if(show_version) {
407                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
408                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
409                 printf(_("Copyright (C) 1998-2003 Ivo Timmermans, Guus Sliepen and others.\n"
410                                 "See the AUTHORS file for a complete list.\n\n"
411                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
412                                 "and you are welcome to redistribute it under certain conditions;\n"
413                                 "see the file COPYING for details.\n"));
414
415                 return 0;
416         }
417
418         if(show_help) {
419                 usage(false);
420                 return 0;
421         }
422
423         if(kill_tincd)
424                 return !kill_other(kill_tincd);
425
426         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
427
428         /* Lock all pages into memory if requested */
429
430         if(do_mlock)
431 #ifdef HAVE_MLOCKALL
432                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
433                         logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
434                                    strerror(errno));
435 #else
436         {
437                 logger(LOG_ERR, _("mlockall() not supported on this platform!"));
438 #endif
439                 return -1;
440         }
441
442         g_argv = argv;
443
444         init_configuration(&config_tree);
445
446         /* Slllluuuuuuurrrrp! */
447
448         RAND_load_file("/dev/urandom", 1024);
449
450         OpenSSL_add_all_algorithms();
451
452         if(generate_keys) {
453                 read_server_config();
454                 return !keygen(generate_keys);
455         }
456
457         if(!read_server_config())
458                 return 1;
459
460         if(lzo_init() != LZO_E_OK) {
461                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
462                 return 1;
463         }
464
465 #ifdef HAVE_MINGW
466         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
467                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
468                 return 1;
469         }
470
471         if(!do_detach || !init_service())
472                 return main2(argc, argv);
473         else
474                 return 1;
475 }
476
477 int main2(int argc, char **argv)
478 {
479 #endif
480
481         if(!detach())
482                 return 1;
483                 
484
485         /* Setup sockets and open device. If it doesn't work, don't give up but try again. */
486
487         while(!setup_network_connections()) {
488                 if(do_detach) {
489                         logger(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
490                         sleep(maxtimeout);
491                 } else {
492                         logger(LOG_ERR, _("Not restarting."));
493                         return 1;
494                 }
495         }
496
497         /* Start main loop. It only exits when tinc is killed. */
498
499         status = main_loop();
500
501         /* Shutdown properly. */
502
503         close_network_connections();
504
505         ifdebug(CONNECTIONS)
506                 dump_device_stats();
507
508         logger(LOG_NOTICE, _("Terminating"));
509         return status;
510 }