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