Use a mutex to allow the TAP reader to process packets faster on Windows.
[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 #ifndef HAVE_MINGW
43 #include <pwd.h>
44 #include <grp.h>
45 #include <time.h>
46 #endif
47
48 #include <getopt.h>
49 #include "pidfile.h"
50
51 #include "conf.h"
52 #include "device.h"
53 #include "logger.h"
54 #include "net.h"
55 #include "netutl.h"
56 #include "process.h"
57 #include "protocol.h"
58 #include "utils.h"
59 #include "xalloc.h"
60
61 /* The name this program was run with. */
62 char *program_name = NULL;
63
64 /* If nonzero, display usage information and exit. */
65 bool show_help = false;
66
67 /* If nonzero, print the version on standard output and exit.  */
68 bool show_version = false;
69
70 /* If nonzero, it will attempt to kill a running tincd and exit. */
71 int kill_tincd = 0;
72
73 /* If nonzero, generate public/private keypair for this host/net. */
74 int generate_keys = 0;
75
76 /* If nonzero, use null ciphers and skip all key exchanges. */
77 bool bypass_security = false;
78
79 /* If nonzero, disable swapping for this process. */
80 bool do_mlock = false;
81
82 /* If nonzero, chroot to netdir after startup. */
83 static bool do_chroot = false;
84
85 /* If !NULL, do setuid to given user after startup */
86 static const char *switchuser = NULL;
87
88 /* If nonzero, write log entries to a separate file. */
89 bool use_logfile = false;
90
91 char *identname = NULL;                         /* program name for syslog */
92 char *pidfilename = NULL;                       /* pid file location */
93 char *logfilename = NULL;                       /* log file location */
94 char **g_argv;                                  /* a copy of the cmdline arguments */
95
96 static int status;
97
98 static struct option const long_options[] = {
99         {"config", required_argument, NULL, 'c'},
100         {"kill", optional_argument, NULL, 'k'},
101         {"net", required_argument, NULL, 'n'},
102         {"help", no_argument, NULL, 1},
103         {"version", no_argument, NULL, 2},
104         {"no-detach", no_argument, NULL, 'D'},
105         {"generate-keys", optional_argument, NULL, 'K'},
106         {"debug", optional_argument, NULL, 'd'},
107         {"bypass-security", no_argument, NULL, 3},
108         {"mlock", no_argument, NULL, 'L'},
109         {"chroot", no_argument, NULL, 'R'},
110         {"user", required_argument, NULL, 'U'},
111         {"logfile", optional_argument, NULL, 4},
112         {"pidfile", required_argument, NULL, 5},
113         {NULL, 0, NULL, 0}
114 };
115
116 #ifdef HAVE_MINGW
117 static struct WSAData wsa_state;
118 CRITICAL_SECTION mutex;
119 #endif
120
121 static void usage(bool status)
122 {
123         if(status)
124                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
125                                 program_name);
126         else {
127                 printf(_("Usage: %s [option]...\n\n"), program_name);
128                 printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
129                                 "  -D, --no-detach            Don't fork and detach.\n"
130                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
131                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
132                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
133                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
134                                 "  -L, --mlock                Lock tinc into main memory.\n"
135                                 "      --logfile[=FILENAME]   Write log entries to a logfile.\n"
136                                 "      --pidfile=FILENAME     Write PID to FILENAME.\n"
137                                 "  -R, --chroot               chroot to NET dir at startup.\n"
138                                 "  -U, --user=USER            setuid to given USER at startup.\n"
139                                 "      --help                 Display this help and exit.\n"
140                                 "      --version              Output version information and exit.\n\n"));
141                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
142         }
143 }
144
145 static bool parse_options(int argc, char **argv)
146 {
147         int r;
148         int option_index = 0;
149
150         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::RU:", long_options, &option_index)) != EOF) {
151                 switch (r) {
152                         case 0:                         /* long option */
153                                 break;
154
155                         case 'c':                               /* config file */
156                                 confbase = xstrdup(optarg);
157                                 break;
158
159                         case 'D':                               /* no detach */
160                                 do_detach = false;
161                                 break;
162
163                         case 'L':                               /* no detach */
164 #ifndef HAVE_MLOCKALL
165                                 logger(LOG_ERR, _("%s not supported on this platform"), "mlockall()");
166                                 return false;
167 #else
168                                 do_mlock = true;
169                                 break;
170 #endif
171
172                         case 'd':                               /* inc debug level */
173                                 if(optarg)
174                                         debug_level = atoi(optarg);
175                                 else
176                                         debug_level++;
177                                 break;
178
179                         case 'k':                               /* kill old tincds */
180 #ifndef HAVE_MINGW
181                                 if(optarg) {
182                                         if(!strcasecmp(optarg, "HUP"))
183                                                 kill_tincd = SIGHUP;
184                                         else if(!strcasecmp(optarg, "TERM"))
185                                                 kill_tincd = SIGTERM;
186                                         else if(!strcasecmp(optarg, "KILL"))
187                                                 kill_tincd = SIGKILL;
188                                         else if(!strcasecmp(optarg, "USR1"))
189                                                 kill_tincd = SIGUSR1;
190                                         else if(!strcasecmp(optarg, "USR2"))
191                                                 kill_tincd = SIGUSR2;
192                                         else if(!strcasecmp(optarg, "WINCH"))
193                                                 kill_tincd = SIGWINCH;
194                                         else if(!strcasecmp(optarg, "INT"))
195                                                 kill_tincd = SIGINT;
196                                         else if(!strcasecmp(optarg, "ALRM"))
197                                                 kill_tincd = SIGALRM;
198                                         else {
199                                                 kill_tincd = atoi(optarg);
200
201                                                 if(!kill_tincd) {
202                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
203                                                                         optarg);
204                                                         usage(true);
205                                                         return false;
206                                                 }
207                                         }
208                                 } else
209                                         kill_tincd = SIGTERM;
210 #else
211                                         kill_tincd = 1;
212 #endif
213                                 break;
214
215                         case 'n':                               /* net name given */
216                                 netname = xstrdup(optarg);
217                                 break;
218
219                         case 'K':                               /* generate public/private keypair */
220                                 if(optarg) {
221                                         generate_keys = atoi(optarg);
222
223                                         if(generate_keys < 512) {
224                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
225                                                                 optarg);
226                                                 usage(true);
227                                                 return false;
228                                         }
229
230                                         generate_keys &= ~7;    /* Round it to bytes */
231                                 } else
232                                         generate_keys = 1024;
233                                 break;
234
235                         case 'R':                               /* chroot to NETNAME dir */
236                                 do_chroot = true;
237                                 break;
238
239                         case 'U':                               /* setuid to USER */
240                                 switchuser = optarg;
241                                 break;
242
243                         case 1:                                 /* show help */
244                                 show_help = true;
245                                 break;
246
247                         case 2:                                 /* show version */
248                                 show_version = true;
249                                 break;
250
251                         case 3:                                 /* bypass security */
252                                 bypass_security = true;
253                                 break;
254
255                         case 4:                                 /* write log entries to a file */
256                                 use_logfile = true;
257                                 if(optarg)
258                                         logfilename = xstrdup(optarg);
259                                 break;
260
261                         case 5:                                 /* write PID to a file */
262                                 pidfilename = xstrdup(optarg);
263                                 break;
264
265                         case '?':
266                                 usage(true);
267                                 return false;
268
269                         default:
270                                 break;
271                 }
272         }
273
274         return true;
275 }
276
277 /* This function prettyprints the key generation process */
278
279 static void indicator(int a, int b, void *p)
280 {
281         switch (a) {
282                 case 0:
283                         fprintf(stderr, ".");
284                         break;
285
286                 case 1:
287                         fprintf(stderr, "+");
288                         break;
289
290                 case 2:
291                         fprintf(stderr, "-");
292                         break;
293
294                 case 3:
295                         switch (b) {
296                                 case 0:
297                                         fprintf(stderr, " p\n");
298                                         break;
299
300                                 case 1:
301                                         fprintf(stderr, " q\n");
302                                         break;
303
304                                 default:
305                                         fprintf(stderr, "?");
306                         }
307                         break;
308
309                 default:
310                         fprintf(stderr, "?");
311         }
312 }
313
314 /*
315   Generate a public/private RSA keypair, and ask for a file to store
316   them in.
317 */
318 static bool keygen(int bits)
319 {
320         RSA *rsa_key;
321         FILE *f;
322         char *name = NULL;
323         char *filename;
324
325         get_config_string(lookup_config(config_tree, "Name"), &name);
326
327         if(name && !check_id(name)) {
328                 fprintf(stderr, _("Invalid name for myself!\n"));
329                 return false;
330         }
331
332         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
333         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
334
335         if(!rsa_key) {
336                 fprintf(stderr, _("Error during key generation!\n"));
337                 return false;
338         } else
339                 fprintf(stderr, _("Done.\n"));
340
341         xasprintf(&filename, "%s/rsa_key.priv", confbase);
342         f = ask_and_open(filename, _("private RSA key"));
343
344         if(!f)
345                 return false;
346
347         if(disable_old_keys(f))
348                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
349   
350 #ifdef HAVE_FCHMOD
351         /* Make it unreadable for others. */
352         fchmod(fileno(f), 0600);
353 #endif
354                 
355         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
356         fclose(f);
357         free(filename);
358
359         if(name)
360                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
361         else
362                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
363
364         f = ask_and_open(filename, _("public RSA key"));
365
366         if(!f)
367                 return false;
368
369         if(disable_old_keys(f))
370                 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
371
372         PEM_write_RSAPublicKey(f, rsa_key);
373         fclose(f);
374         free(filename);
375         if(name)
376                 free(name);
377
378         return true;
379 }
380
381 /*
382   Set all files and paths according to netname
383 */
384 static void make_names(void)
385 {
386 #ifdef HAVE_MINGW
387         HKEY key;
388         char installdir[1024] = "";
389         long len = sizeof(installdir);
390 #endif
391
392         if(netname)
393                 xasprintf(&identname, "tinc.%s", netname);
394         else
395                 identname = xstrdup("tinc");
396
397 #ifdef HAVE_MINGW
398         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
399                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
400                         if(!logfilename)
401                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
402                         if(!confbase) {
403                                 if(netname)
404                                         xasprintf(&confbase, "%s/%s", installdir, netname);
405                                 else
406                                         xasprintf(&confbase, "%s", installdir);
407                         }
408                 }
409                 RegCloseKey(key);
410                 if(*installdir)
411                         return;
412         }
413 #endif
414
415         if(!pidfilename)
416                 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
417
418         if(!logfilename)
419                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
420
421         if(netname) {
422                 if(!confbase)
423                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
424                 else
425                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
426         } else {
427                 if(!confbase)
428                         xasprintf(&confbase, CONFDIR "/tinc");
429         }
430 }
431
432 static void free_names() {
433         if (identname) free(identname);
434         if (netname) free(netname);
435         if (pidfilename) free(pidfilename);
436         if (logfilename) free(logfilename);
437         if (confbase) free(confbase);
438 }
439
440 static bool drop_privs() {
441 #ifdef HAVE_MINGW
442         if (switchuser) {
443                 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
444                 return false;
445         }
446         if (do_chroot) {
447                 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
448                 return false;
449         }
450 #else
451         uid_t uid = 0;
452         if (switchuser) {
453                 struct passwd *pw = getpwnam(switchuser);
454                 if (!pw) {
455                         logger(LOG_ERR, _("unknown user `%s'"), switchuser);
456                         return false;
457                 }
458                 uid = pw->pw_uid;
459                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
460                     setgid(pw->pw_gid) != 0) {
461                         logger(LOG_ERR, _("System call `%s' failed: %s"),
462                                "initgroups", strerror(errno));
463                         return false;
464                 }
465                 endgrent();
466                 endpwent();
467         }
468         if (do_chroot) {
469                 tzset();        /* for proper timestamps in logs */
470                 if (chroot(confbase) != 0 || chdir("/") != 0) {
471                         logger(LOG_ERR, _("System call `%s' failed: %s"),
472                                "chroot", strerror(errno));
473                         return false;
474                 }
475                 free(confbase);
476                 confbase = xstrdup("");
477         }
478         if (switchuser)
479                 if (setuid(uid) != 0) {
480                         logger(LOG_ERR, _("System call `%s' failed: %s"),
481                                "setuid", strerror(errno));
482                         return false;
483                 }
484 #endif
485         return true;
486 }
487
488 #ifdef HAVE_MINGW
489 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
490 #else
491 # define NORMAL_PRIORITY_CLASS 0
492 # define BELOW_NORMAL_PRIORITY_CLASS 10
493 # define HIGH_PRIORITY_CLASS -10
494 # define setpriority(level) nice(level)
495 #endif
496
497 int main(int argc, char **argv)
498 {
499         program_name = argv[0];
500
501         setlocale(LC_ALL, "");
502         bindtextdomain(PACKAGE, LOCALEDIR);
503         textdomain(PACKAGE);
504
505         if(!parse_options(argc, argv))
506                 return 1;
507         
508         make_names();
509
510         if(show_version) {
511                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
512                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
513                 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
514                                 "See the AUTHORS file for a complete list.\n\n"
515                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
516                                 "and you are welcome to redistribute it under certain conditions;\n"
517                                 "see the file COPYING for details.\n"));
518
519                 return 0;
520         }
521
522         if(show_help) {
523                 usage(false);
524                 return 0;
525         }
526
527         if(kill_tincd)
528                 return !kill_other(kill_tincd);
529
530         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
531
532         g_argv = argv;
533
534         init_configuration(&config_tree);
535
536         /* Slllluuuuuuurrrrp! */
537
538         RAND_load_file("/dev/urandom", 1024);
539
540         ENGINE_load_builtin_engines();
541         ENGINE_register_all_complete();
542
543         OpenSSL_add_all_algorithms();
544
545         if(generate_keys) {
546                 read_server_config();
547                 return !keygen(generate_keys);
548         }
549
550         if(!read_server_config())
551                 return 1;
552
553         if(lzo_init() != LZO_E_OK) {
554                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
555                 return 1;
556         }
557
558 #ifdef HAVE_MINGW
559         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
560                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
561                 return 1;
562         }
563
564         if(!do_detach || !init_service())
565                 return main2(argc, argv);
566         else
567                 return 1;
568 }
569
570 int main2(int argc, char **argv)
571 {
572         InitializeCriticalSection(&mutex);
573         EnterCriticalSection(&mutex);
574 #endif
575
576         if(!detach())
577                 return 1;
578
579 #ifdef HAVE_MLOCKALL
580         /* Lock all pages into memory if requested.
581          * This has to be done after daemon()/fork() so it works for child.
582          * No need to do that in parent as it's very short-lived. */
583         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
584                 logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
585                    strerror(errno));
586                 return 1;
587         }
588 #endif
589
590         /* Setup sockets and open device. */
591
592         if(!setup_network())
593                 goto end;
594
595         /* Initiate all outgoing connections. */
596
597         try_outgoing_connections();
598
599         /* Change process priority */
600
601         char *priority = 0;
602
603         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
604                 if(!strcasecmp(priority, "Normal"))
605                         setpriority(NORMAL_PRIORITY_CLASS);
606                 else if(!strcasecmp(priority, "Low"))
607                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
608                 else if(!strcasecmp(priority, "High"))
609                         setpriority(HIGH_PRIORITY_CLASS);
610                 else {
611                         logger(LOG_ERR, _("Invalid priority `%s`!"), priority);
612                         goto end;
613                 }
614         }
615
616         /* drop privileges */
617         if (!drop_privs())
618                 goto end;
619
620         /* Start main loop. It only exits when tinc is killed. */
621
622         status = main_loop();
623
624         /* Shutdown properly. */
625
626         ifdebug(CONNECTIONS)
627                 dump_device_stats();
628
629         close_network_connections();
630
631 end:
632         logger(LOG_NOTICE, _("Terminating"));
633
634 #ifndef HAVE_MINGW
635         remove_pid(pidfilename);
636 #endif
637
638         EVP_cleanup();
639         ENGINE_cleanup();
640         CRYPTO_cleanup_all_ex_data();
641         ERR_remove_state(0);
642         ERR_free_strings();
643
644         exit_configuration(&config_tree);
645         free_names();
646
647         return status;
648 }