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