2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2018 Guus Sliepen <guus@tinc-vpn.org>
5 2008 Max Rijevski <maksuf@gmail.com>
6 2009 Michael Tokarev <mjt@tls.msk.ru>
7 2010 Julien Muchembled <jm@jmuchemb.eu>
8 2010 Timothy Redaelli <timothy@redaelli.eu>
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License along
21 with this program; if not, write to the Free Software Foundation, Inc.,
22 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 /* Darwin (MacOS/X) needs the following definition... */
28 #ifndef _P1003_1B_VISIBLE
29 #define _P1003_1B_VISIBLE
32 #ifdef HAVE_SYS_MMAN_H
36 #include <openssl/rand.h>
37 #include <openssl/rsa.h>
38 #include <openssl/pem.h>
39 #include <openssl/evp.h>
40 #include <openssl/engine.h>
52 #ifdef HAVE_GETOPT_LONG
70 /* The name this program was run with. */
71 char *program_name = NULL;
73 /* If nonzero, display usage information and exit. */
74 bool show_help = false;
76 /* If nonzero, print the version on standard output and exit. */
77 bool show_version = false;
79 /* If nonzero, it will attempt to kill a running tincd and exit. */
82 /* If nonzero, generate public/private keypair for this host/net. */
83 int generate_keys = 0;
85 /* If nonzero, use null ciphers and skip all key exchanges. */
86 bool bypass_security = false;
88 /* If nonzero, disable swapping for this process. */
89 bool do_mlock = false;
91 /* If nonzero, chroot to netdir after startup. */
92 static bool do_chroot = false;
94 /* If !NULL, do setuid to given user after startup */
95 static const char *switchuser = NULL;
97 /* If nonzero, write log entries to a separate file. */
98 bool use_logfile = false;
100 char *identname = NULL; /* program name for syslog */
101 char *pidfilename = NULL; /* pid file location */
102 char *logfilename = NULL; /* log file location */
103 char **g_argv; /* a copy of the cmdline arguments */
105 static int status = 1;
107 static struct option const long_options[] = {
108 {"config", required_argument, NULL, 'c'},
109 {"kill", optional_argument, NULL, 'k'},
110 {"net", required_argument, NULL, 'n'},
111 {"help", no_argument, NULL, 1},
112 {"version", no_argument, NULL, 2},
113 {"no-detach", no_argument, NULL, 'D'},
114 {"generate-keys", optional_argument, NULL, 'K'},
115 {"debug", optional_argument, NULL, 'd'},
116 {"bypass-security", no_argument, NULL, 3},
117 {"mlock", no_argument, NULL, 'L'},
118 {"chroot", no_argument, NULL, 'R'},
119 {"user", required_argument, NULL, 'U'},
120 {"logfile", optional_argument, NULL, 4},
121 {"pidfile", required_argument, NULL, 5},
122 {"option", required_argument, NULL, 'o'},
127 static struct WSAData wsa_state;
128 CRITICAL_SECTION mutex;
129 int main2(int argc, char **argv);
132 static void usage(bool status) {
134 fprintf(stderr, "Try `%s --help\' for more information.\n",
137 printf("Usage: %s [option]...\n\n", program_name);
138 printf(" -c, --config=DIR Read configuration options from DIR.\n"
139 " -D, --no-detach Don't fork and detach.\n"
140 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
141 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
142 " -n, --net=NETNAME Connect to net NETNAME.\n"
143 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
144 " -L, --mlock Lock tinc into main memory.\n"
145 " --logfile[=FILENAME] Write log entries to a logfile.\n"
146 " --pidfile=FILENAME Write PID to FILENAME.\n"
147 " -o, --option=[HOST.]KEY=VALUE Set global/host configuration value.\n"
148 " -R, --chroot chroot to NET dir at startup.\n"
149 " -U, --user=USER setuid to given USER at startup.\n"
150 " --help Display this help and exit.\n"
151 " --version Output version information and exit.\n\n");
152 printf("Report bugs to tinc@tinc-vpn.org.\n");
156 static bool parse_options(int argc, char **argv) {
159 int option_index = 0;
162 cmdline_conf = list_alloc((list_action_t)free_config);
164 while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
166 case 0: /* long option */
169 case 'c': /* config file */
171 fprintf(stderr, "Only one configuration directory can be given.\n");
176 confbase = xstrdup(optarg);
179 case 'D': /* no detach */
183 case 'L': /* no detach */
184 #ifndef HAVE_MLOCKALL
185 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
192 case 'd': /* increase debug level */
193 if(!optarg && optind < argc && *argv[optind] != '-') {
194 optarg = argv[optind++];
198 debug_level = atoi(optarg);
205 case 'k': /* kill old tincds */
207 if(!optarg && optind < argc && *argv[optind] != '-') {
208 optarg = argv[optind++];
212 if(!strcasecmp(optarg, "HUP")) {
214 } else if(!strcasecmp(optarg, "TERM")) {
215 kill_tincd = SIGTERM;
216 } else if(!strcasecmp(optarg, "KILL")) {
217 kill_tincd = SIGKILL;
218 } else if(!strcasecmp(optarg, "USR1")) {
219 kill_tincd = SIGUSR1;
220 } else if(!strcasecmp(optarg, "USR2")) {
221 kill_tincd = SIGUSR2;
222 } else if(!strcasecmp(optarg, "WINCH")) {
223 kill_tincd = SIGWINCH;
224 } else if(!strcasecmp(optarg, "INT")) {
226 } else if(!strcasecmp(optarg, "ALRM")) {
227 kill_tincd = SIGALRM;
228 } else if(!strcasecmp(optarg, "ABRT")) {
229 kill_tincd = SIGABRT;
231 kill_tincd = atoi(optarg);
234 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
241 kill_tincd = SIGTERM;
249 case 'n': /* net name given */
251 /* netname "." is special: a "top-level name" */
253 fprintf(stderr, "Only one netname can be given.\n");
258 if(optarg && strcmp(optarg, ".")) {
259 netname = xstrdup(optarg);
264 case 'o': /* option */
265 cfg = parse_config_line(optarg, NULL, ++lineno);
271 list_insert_tail(cmdline_conf, cfg);
274 case 'K': /* generate public/private keypair */
275 if(!optarg && optind < argc && *argv[optind] != '-') {
276 optarg = argv[optind++];
280 generate_keys = atoi(optarg);
282 if(generate_keys < 512) {
283 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
289 generate_keys &= ~7; /* Round it to bytes */
291 generate_keys = 2048;
296 case 'R': /* chroot to NETNAME dir */
300 case 'U': /* setuid to USER */
304 case 1: /* show help */
308 case 2: /* show version */
312 case 3: /* bypass security */
313 bypass_security = true;
316 case 4: /* write log entries to a file */
319 if(!optarg && optind < argc && *argv[optind] != '-') {
320 optarg = argv[optind++];
325 fprintf(stderr, "Only one logfile can be given.\n");
330 logfilename = xstrdup(optarg);
335 case 5: /* write PID to a file */
337 fprintf(stderr, "Only one pidfile can be given.\n");
342 pidfilename = xstrdup(optarg);
355 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
363 /* This function prettyprints the key generation process */
365 static int indicator(int a, int b, BN_GENCB *cb) {
370 fprintf(stderr, ".");
374 fprintf(stderr, "+");
378 fprintf(stderr, "-");
384 fprintf(stderr, " p\n");
388 fprintf(stderr, " q\n");
392 fprintf(stderr, "?");
398 fprintf(stderr, "?");
404 #ifndef HAVE_BN_GENCB_NEW
405 BN_GENCB *BN_GENCB_new(void) {
406 return xmalloc_and_zero(sizeof(BN_GENCB));
409 void BN_GENCB_free(BN_GENCB *cb) {
415 Generate a public/private RSA keypair, and ask for a file to store
418 static bool keygen(int bits) {
422 char filename[PATH_MAX];
426 fprintf(stderr, "Generating %d bits keys:\n", bits);
434 BN_GENCB_set(cb, indicator, NULL);
438 if(BN_hex2bn(&e, "10001") == 0) {
446 result = RSA_generate_key_ex(rsa_key, bits, e, cb);
452 fprintf(stderr, "Error during key generation!\n");
456 fprintf(stderr, "Done.\n");
459 snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
460 f = ask_and_open(filename, "private RSA key");
468 /* Make it unreadable for others. */
469 fchmod(fileno(f), 0600);
473 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
476 char *name = get_name();
479 snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
482 snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
485 f = ask_and_open(filename, "public RSA key");
493 PEM_write_RSAPublicKey(f, rsa_key);
502 Set all files and paths according to netname
504 static void make_names(void) {
507 char installdir[1024] = "";
508 DWORD len = sizeof(installdir);
512 xasprintf(&identname, "tinc.%s", netname);
514 identname = xstrdup("tinc");
519 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
520 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
523 xasprintf(&confbase, "%s/%s", installdir, netname);
525 xasprintf(&confbase, "%s", installdir);
530 xasprintf(&logfilename, "%s/tinc.log", confbase);
544 xasprintf(&pidfilename, RUNSTATEDIR "/%s.pid", identname);
548 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
553 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
555 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
559 xasprintf(&confbase, CONFDIR "/tinc");
564 static void free_names() {
572 static bool drop_privs() {
576 logger(LOG_ERR, "%s not supported on this platform", "-U");
581 logger(LOG_ERR, "%s not supported on this platform", "-R");
589 struct passwd *pw = getpwnam(switchuser);
592 logger(LOG_ERR, "unknown user `%s'", switchuser);
598 if(initgroups(switchuser, pw->pw_gid) != 0 ||
599 setgid(pw->pw_gid) != 0) {
600 logger(LOG_ERR, "System call `%s' failed: %s",
601 "initgroups", strerror(errno));
606 // Not supported in android NDK
613 tzset(); /* for proper timestamps in logs */
615 if(chroot(confbase) != 0 || chdir("/") != 0) {
616 logger(LOG_ERR, "System call `%s' failed: %s",
617 "chroot", strerror(errno));
622 confbase = xstrdup("");
626 if(setuid(uid) != 0) {
627 logger(LOG_ERR, "System call `%s' failed: %s",
628 "setuid", strerror(errno));
637 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
639 # define NORMAL_PRIORITY_CLASS 0
640 # define BELOW_NORMAL_PRIORITY_CLASS 10
641 # define HIGH_PRIORITY_CLASS -10
642 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
645 int main(int argc, char **argv) {
646 program_name = argv[0];
648 if(!parse_options(argc, argv)) {
653 printf("%s version %s\n", PACKAGE, VERSION);
654 printf("Copyright (C) 1998-2018 Ivo Timmermans, Guus Sliepen and others.\n"
655 "See the AUTHORS file for a complete list.\n\n"
656 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
657 "and you are welcome to redistribute it under certain conditions;\n"
658 "see the file COPYING for details.\n");
671 return !kill_other(kill_tincd);
674 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
678 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
683 unsetenv("LISTEN_PID");
686 init_configuration(&config_tree);
688 ENGINE_load_builtin_engines();
689 ENGINE_register_all_complete();
691 OpenSSL_add_all_algorithms();
694 read_server_config();
695 return !keygen(generate_keys);
698 if(!read_server_config()) {
704 if(lzo_init() != LZO_E_OK) {
705 logger(LOG_ERR, "Error initializing LZO compressor!");
713 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
714 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
718 if(!do_detach || !init_service()) {
719 return main2(argc, argv);
725 int main2(int argc, char **argv) {
726 InitializeCriticalSection(&mutex);
727 EnterCriticalSection(&mutex);
729 char *priority = NULL;
737 /* Lock all pages into memory if requested.
738 * This has to be done after daemon()/fork() so it works for child.
739 * No need to do that in parent as it's very short-lived. */
740 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
741 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
748 /* Setup sockets and open device. */
750 if(!setup_network()) {
754 /* Initiate all outgoing connections. */
756 try_outgoing_connections();
758 /* Change process priority */
760 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
761 if(!strcasecmp(priority, "Normal")) {
762 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
763 logger(LOG_ERR, "System call `%s' failed: %s",
764 "setpriority", strerror(errno));
767 } else if(!strcasecmp(priority, "Low")) {
768 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
769 logger(LOG_ERR, "System call `%s' failed: %s",
770 "setpriority", strerror(errno));
773 } else if(!strcasecmp(priority, "High")) {
774 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
775 logger(LOG_ERR, "System call `%s' failed: %s",
776 "setpriority", strerror(errno));
780 logger(LOG_ERR, "Invalid priority `%s`!", priority);
785 /* drop privileges */
790 /* Start main loop. It only exits when tinc is killed. */
792 status = main_loop();
794 /* Shutdown properly. */
799 close_network_connections();
802 logger(LOG_NOTICE, "Terminating");
805 remove_pid(pidfilename);
814 exit_configuration(&config_tree);
815 list_delete_list(cmdline_conf);