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