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 2009 Michael Tokarev <mjt@tls.msk.ru>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 /* Darwin (MacOS/X) needs the following definition... */
27 #ifndef _P1003_1B_VISIBLE
28 #define _P1003_1B_VISIBLE
31 #ifdef HAVE_SYS_MMAN_H
35 #include <openssl/rand.h>
36 #include <openssl/rsa.h>
37 #include <openssl/pem.h>
38 #include <openssl/evp.h>
39 #include <openssl/engine.h>
62 /* The name this program was run with. */
63 char *program_name = NULL;
65 /* If nonzero, display usage information and exit. */
66 bool show_help = false;
68 /* If nonzero, print the version on standard output and exit. */
69 bool show_version = false;
71 /* If nonzero, it will attempt to kill a running tincd and exit. */
74 /* If nonzero, generate public/private keypair for this host/net. */
75 int generate_keys = 0;
77 /* If nonzero, use null ciphers and skip all key exchanges. */
78 bool bypass_security = false;
80 /* If nonzero, disable swapping for this process. */
81 bool do_mlock = false;
83 /* If nonzero, chroot to netdir after startup. */
84 static bool do_chroot = false;
86 /* If !NULL, do setuid to given user after startup */
87 static const char *switchuser = NULL;
89 /* If nonzero, write log entries to a separate file. */
90 bool use_logfile = false;
92 char *identname = NULL; /* program name for syslog */
93 char *pidfilename = NULL; /* pid file location */
94 char *logfilename = NULL; /* log file location */
95 char **g_argv; /* a copy of the cmdline arguments */
99 static struct option const long_options[] = {
100 {"config", required_argument, NULL, 'c'},
101 {"kill", optional_argument, NULL, 'k'},
102 {"net", required_argument, NULL, 'n'},
103 {"help", no_argument, NULL, 1},
104 {"version", no_argument, NULL, 2},
105 {"no-detach", no_argument, NULL, 'D'},
106 {"generate-keys", optional_argument, NULL, 'K'},
107 {"debug", optional_argument, NULL, 'd'},
108 {"bypass-security", no_argument, NULL, 3},
109 {"mlock", no_argument, NULL, 'L'},
110 {"chroot", no_argument, NULL, 'R'},
111 {"user", required_argument, NULL, 'U'},
112 {"logfile", optional_argument, NULL, 4},
113 {"pidfile", required_argument, NULL, 5},
118 static struct WSAData wsa_state;
119 CRITICAL_SECTION mutex;
122 static void usage(bool status)
125 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
128 printf(_("Usage: %s [option]...\n\n"), program_name);
129 printf(_(" -c, --config=DIR Read configuration options from DIR.\n"
130 " -D, --no-detach Don't fork and detach.\n"
131 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
132 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
133 " -n, --net=NETNAME Connect to net NETNAME.\n"
134 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
135 " -L, --mlock Lock tinc into main memory.\n"
136 " --logfile[=FILENAME] Write log entries to a logfile.\n"
137 " --pidfile=FILENAME Write PID to FILENAME.\n"
138 " -R, --chroot chroot to NET dir at startup.\n"
139 " -U, --user=USER setuid to given USER at startup.\n"
140 " --help Display this help and exit.\n"
141 " --version Output version information and exit.\n\n"));
142 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
146 static bool parse_options(int argc, char **argv)
149 int option_index = 0;
151 while((r = getopt_long(argc, argv, "c:DLd::k::n:K::RU:", long_options, &option_index)) != EOF) {
153 case 0: /* long option */
156 case 'c': /* config file */
157 confbase = xstrdup(optarg);
160 case 'D': /* no detach */
164 case 'L': /* no detach */
165 #ifndef HAVE_MLOCKALL
166 logger(LOG_ERR, _("%s not supported on this platform"), "mlockall()");
173 case 'd': /* inc debug level */
175 debug_level = atoi(optarg);
180 case 'k': /* kill old tincds */
183 if(!strcasecmp(optarg, "HUP"))
185 else if(!strcasecmp(optarg, "TERM"))
186 kill_tincd = SIGTERM;
187 else if(!strcasecmp(optarg, "KILL"))
188 kill_tincd = SIGKILL;
189 else if(!strcasecmp(optarg, "USR1"))
190 kill_tincd = SIGUSR1;
191 else if(!strcasecmp(optarg, "USR2"))
192 kill_tincd = SIGUSR2;
193 else if(!strcasecmp(optarg, "WINCH"))
194 kill_tincd = SIGWINCH;
195 else if(!strcasecmp(optarg, "INT"))
197 else if(!strcasecmp(optarg, "ALRM"))
198 kill_tincd = SIGALRM;
200 kill_tincd = atoi(optarg);
203 fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
210 kill_tincd = SIGTERM;
216 case 'n': /* net name given */
217 netname = xstrdup(optarg);
220 case 'K': /* generate public/private keypair */
222 generate_keys = atoi(optarg);
224 if(generate_keys < 512) {
225 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
231 generate_keys &= ~7; /* Round it to bytes */
233 generate_keys = 2048;
236 case 'R': /* chroot to NETNAME dir */
240 case 'U': /* setuid to USER */
244 case 1: /* show help */
248 case 2: /* show version */
252 case 3: /* bypass security */
253 bypass_security = true;
256 case 4: /* write log entries to a file */
259 logfilename = xstrdup(optarg);
262 case 5: /* write PID to a file */
263 pidfilename = xstrdup(optarg);
278 /* This function prettyprints the key generation process */
280 static void indicator(int a, int b, void *p)
284 fprintf(stderr, ".");
288 fprintf(stderr, "+");
292 fprintf(stderr, "-");
298 fprintf(stderr, " p\n");
302 fprintf(stderr, " q\n");
306 fprintf(stderr, "?");
311 fprintf(stderr, "?");
316 Generate a public/private RSA keypair, and ask for a file to store
319 static bool keygen(int bits)
326 get_config_string(lookup_config(config_tree, "Name"), &name);
328 if(name && !check_id(name)) {
329 fprintf(stderr, _("Invalid name for myself!\n"));
333 fprintf(stderr, _("Generating %d bits keys:\n"), bits);
334 rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
337 fprintf(stderr, _("Error during key generation!\n"));
340 fprintf(stderr, _("Done.\n"));
342 xasprintf(&filename, "%s/rsa_key.priv", confbase);
343 f = ask_and_open(filename, _("private RSA key"));
348 if(disable_old_keys(f))
349 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
352 /* Make it unreadable for others. */
353 fchmod(fileno(f), 0600);
356 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
361 xasprintf(&filename, "%s/hosts/%s", confbase, name);
363 xasprintf(&filename, "%s/rsa_key.pub", confbase);
365 f = ask_and_open(filename, _("public RSA key"));
370 if(disable_old_keys(f))
371 fprintf(stderr, _("Warning: old key(s) found and disabled.\n"));
373 PEM_write_RSAPublicKey(f, rsa_key);
383 Set all files and paths according to netname
385 static void make_names(void)
389 char installdir[1024] = "";
390 long len = sizeof(installdir);
394 xasprintf(&identname, "tinc.%s", netname);
396 identname = xstrdup("tinc");
399 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
400 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
402 xasprintf(&logfilename, "%s/log/%s.log", identname);
405 xasprintf(&confbase, "%s/%s", installdir, netname);
407 xasprintf(&confbase, "%s", installdir);
417 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
420 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
424 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
426 logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
429 xasprintf(&confbase, CONFDIR "/tinc");
433 static void free_names() {
434 if (identname) free(identname);
435 if (netname) free(netname);
436 if (pidfilename) free(pidfilename);
437 if (logfilename) free(logfilename);
438 if (confbase) free(confbase);
441 static bool drop_privs() {
444 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
448 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
454 struct passwd *pw = getpwnam(switchuser);
456 logger(LOG_ERR, _("unknown user `%s'"), switchuser);
460 if (initgroups(switchuser, pw->pw_gid) != 0 ||
461 setgid(pw->pw_gid) != 0) {
462 logger(LOG_ERR, _("System call `%s' failed: %s"),
463 "initgroups", strerror(errno));
470 tzset(); /* for proper timestamps in logs */
471 if (chroot(confbase) != 0 || chdir("/") != 0) {
472 logger(LOG_ERR, _("System call `%s' failed: %s"),
473 "chroot", strerror(errno));
477 confbase = xstrdup("");
480 if (setuid(uid) != 0) {
481 logger(LOG_ERR, _("System call `%s' failed: %s"),
482 "setuid", strerror(errno));
490 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
492 # define NORMAL_PRIORITY_CLASS 0
493 # define BELOW_NORMAL_PRIORITY_CLASS 10
494 # define HIGH_PRIORITY_CLASS -10
495 # define setpriority(level) nice(level)
498 int main(int argc, char **argv)
500 program_name = argv[0];
502 setlocale(LC_ALL, "");
503 bindtextdomain(PACKAGE, LOCALEDIR);
506 if(!parse_options(argc, argv))
512 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
513 VERSION, __DATE__, __TIME__, PROT_CURRENT);
514 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
515 "See the AUTHORS file for a complete list.\n\n"
516 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
517 "and you are welcome to redistribute it under certain conditions;\n"
518 "see the file COPYING for details.\n"));
529 return !kill_other(kill_tincd);
531 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
535 init_configuration(&config_tree);
537 /* Slllluuuuuuurrrrp! */
539 RAND_load_file("/dev/urandom", 1024);
541 ENGINE_load_builtin_engines();
542 ENGINE_register_all_complete();
544 OpenSSL_add_all_algorithms();
547 read_server_config();
548 return !keygen(generate_keys);
551 if(!read_server_config())
554 if(lzo_init() != LZO_E_OK) {
555 logger(LOG_ERR, _("Error initializing LZO compressor!"));
560 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
561 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
565 if(!do_detach || !init_service())
566 return main2(argc, argv);
571 int main2(int argc, char **argv)
573 InitializeCriticalSection(&mutex);
574 EnterCriticalSection(&mutex);
581 /* Lock all pages into memory if requested.
582 * This has to be done after daemon()/fork() so it works for child.
583 * No need to do that in parent as it's very short-lived. */
584 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
585 logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
591 /* Setup sockets and open device. */
596 /* Initiate all outgoing connections. */
598 try_outgoing_connections();
600 /* Change process priority */
604 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
605 if(!strcasecmp(priority, "Normal"))
606 setpriority(NORMAL_PRIORITY_CLASS);
607 else if(!strcasecmp(priority, "Low"))
608 setpriority(BELOW_NORMAL_PRIORITY_CLASS);
609 else if(!strcasecmp(priority, "High"))
610 setpriority(HIGH_PRIORITY_CLASS);
612 logger(LOG_ERR, _("Invalid priority `%s`!"), priority);
617 /* drop privileges */
621 /* Start main loop. It only exits when tinc is killed. */
623 status = main_loop();
625 /* Shutdown properly. */
630 close_network_connections();
633 logger(LOG_NOTICE, _("Terminating"));
636 remove_pid(pidfilename);
641 CRYPTO_cleanup_all_ex_data();
645 exit_configuration(&config_tree);