2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2019 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>
41 #include <openssl/bn.h>
53 #ifdef HAVE_GETOPT_LONG
71 /* The name this program was run with. */
72 char *program_name = NULL;
74 /* If nonzero, display usage information and exit. */
75 bool show_help = false;
77 /* If nonzero, print the version on standard output and exit. */
78 bool show_version = false;
80 /* If nonzero, it will attempt to kill a running tincd and exit. */
83 /* If nonzero, generate public/private keypair for this host/net. */
84 int generate_keys = 0;
86 /* If nonzero, use null ciphers and skip all key exchanges. */
87 bool bypass_security = false;
89 /* If nonzero, disable swapping for this process. */
90 bool do_mlock = false;
92 /* If nonzero, chroot to netdir after startup. */
93 static bool do_chroot = false;
95 /* If !NULL, do setuid to given user after startup */
96 static const char *switchuser = NULL;
98 /* If nonzero, write log entries to a separate file. */
99 bool use_logfile = false;
101 char *identname = NULL; /* program name for syslog */
102 char *pidfilename = NULL; /* pid file location */
103 char *logfilename = NULL; /* log file location */
104 char **g_argv; /* a copy of the cmdline arguments */
106 static int status = 1;
108 static struct option const long_options[] = {
109 {"config", required_argument, NULL, 'c'},
110 {"kill", optional_argument, NULL, 'k'},
111 {"net", required_argument, NULL, 'n'},
112 {"help", no_argument, NULL, 1},
113 {"version", no_argument, NULL, 2},
114 {"no-detach", no_argument, NULL, 'D'},
115 {"generate-keys", optional_argument, NULL, 'K'},
116 {"debug", optional_argument, NULL, 'd'},
117 {"bypass-security", no_argument, NULL, 3},
118 {"mlock", no_argument, NULL, 'L'},
119 {"chroot", no_argument, NULL, 'R'},
120 {"user", required_argument, NULL, 'U'},
121 {"logfile", optional_argument, NULL, 4},
122 {"pidfile", required_argument, NULL, 5},
123 {"option", required_argument, NULL, 'o'},
128 static struct WSAData wsa_state;
129 CRITICAL_SECTION mutex;
130 int main2(int argc, char **argv);
133 static void usage(bool status) {
135 fprintf(stderr, "Try `%s --help\' for more information.\n",
138 printf("Usage: %s [option]...\n\n", program_name);
139 printf(" -c, --config=DIR Read configuration options from DIR.\n"
140 " -D, --no-detach Don't fork and detach.\n"
141 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
142 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
143 " -n, --net=NETNAME Connect to net NETNAME.\n"
144 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
145 " -L, --mlock Lock tinc into main memory.\n"
146 " --logfile[=FILENAME] Write log entries to a logfile.\n"
147 " --pidfile=FILENAME Write PID to FILENAME.\n"
148 " -o, --option=[HOST.]KEY=VALUE Set global/host configuration value.\n"
149 " -R, --chroot chroot to NET dir at startup.\n"
150 " -U, --user=USER setuid to given USER at startup.\n"
151 " --help Display this help and exit.\n"
152 " --version Output version information and exit.\n\n");
153 printf("Report bugs to tinc@tinc-vpn.org.\n");
157 static bool parse_options(int argc, char **argv) {
160 int option_index = 0;
163 cmdline_conf = list_alloc((list_action_t)free_config);
165 while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
167 case 0: /* long option */
170 case 'c': /* config file */
172 fprintf(stderr, "Only one configuration directory can be given.\n");
177 confbase = xstrdup(optarg);
180 case 'D': /* no detach */
184 case 'L': /* no detach */
185 #ifndef HAVE_MLOCKALL
186 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
193 case 'd': /* increase debug level */
194 if(!optarg && optind < argc && *argv[optind] != '-') {
195 optarg = argv[optind++];
199 debug_level = atoi(optarg);
206 case 'k': /* kill old tincds */
208 if(!optarg && optind < argc && *argv[optind] != '-') {
209 optarg = argv[optind++];
213 if(!strcasecmp(optarg, "HUP")) {
215 } else if(!strcasecmp(optarg, "TERM")) {
216 kill_tincd = SIGTERM;
217 } else if(!strcasecmp(optarg, "KILL")) {
218 kill_tincd = SIGKILL;
219 } else if(!strcasecmp(optarg, "USR1")) {
220 kill_tincd = SIGUSR1;
221 } else if(!strcasecmp(optarg, "USR2")) {
222 kill_tincd = SIGUSR2;
223 } else if(!strcasecmp(optarg, "WINCH")) {
224 kill_tincd = SIGWINCH;
225 } else if(!strcasecmp(optarg, "INT")) {
227 } else if(!strcasecmp(optarg, "ALRM")) {
228 kill_tincd = SIGALRM;
229 } else if(!strcasecmp(optarg, "ABRT")) {
230 kill_tincd = SIGABRT;
232 kill_tincd = atoi(optarg);
235 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
242 kill_tincd = SIGTERM;
250 case 'n': /* net name given */
252 /* netname "." is special: a "top-level name" */
254 fprintf(stderr, "Only one netname can be given.\n");
259 if(optarg && strcmp(optarg, ".")) {
260 netname = xstrdup(optarg);
265 case 'o': /* option */
266 cfg = parse_config_line(optarg, NULL, ++lineno);
272 list_insert_tail(cmdline_conf, cfg);
275 case 'K': /* generate public/private keypair */
276 if(!optarg && optind < argc && *argv[optind] != '-') {
277 optarg = argv[optind++];
281 generate_keys = atoi(optarg);
283 if(generate_keys < 512) {
284 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
290 generate_keys &= ~7; /* Round it to bytes */
292 generate_keys = 2048;
297 case 'R': /* chroot to NETNAME dir */
301 case 'U': /* setuid to USER */
305 case 1: /* show help */
309 case 2: /* show version */
313 case 3: /* bypass security */
314 bypass_security = true;
317 case 4: /* write log entries to a file */
320 if(!optarg && optind < argc && *argv[optind] != '-') {
321 optarg = argv[optind++];
326 fprintf(stderr, "Only one logfile can be given.\n");
331 logfilename = xstrdup(optarg);
336 case 5: /* write PID to a file */
338 fprintf(stderr, "Only one pidfile can be given.\n");
343 pidfilename = xstrdup(optarg);
356 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
364 /* This function prettyprints the key generation process */
366 static int indicator(int a, int b, BN_GENCB *cb) {
371 fprintf(stderr, ".");
375 fprintf(stderr, "+");
379 fprintf(stderr, "-");
385 fprintf(stderr, " p\n");
389 fprintf(stderr, " q\n");
393 fprintf(stderr, "?");
399 fprintf(stderr, "?");
406 Generate a public/private RSA keypair, and ask for a file to store
409 static bool keygen(int bits) {
413 char filename[PATH_MAX];
417 fprintf(stderr, "Generating %d bits keys:\n", bits);
425 BN_GENCB_set(cb, indicator, NULL);
429 if(BN_hex2bn(&e, "10001") == 0) {
437 result = RSA_generate_key_ex(rsa_key, bits, e, cb);
443 fprintf(stderr, "Error during key generation!\n");
447 fprintf(stderr, "Done.\n");
450 snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
451 f = ask_and_open(filename, "private RSA key");
459 /* Make it unreadable for others. */
460 fchmod(fileno(f), 0600);
464 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
467 char *name = get_name();
470 snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
473 snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
476 f = ask_and_open(filename, "public RSA key");
484 PEM_write_RSAPublicKey(f, rsa_key);
493 Set all files and paths according to netname
495 static void make_names(void) {
498 char installdir[1024] = "";
499 DWORD len = sizeof(installdir);
503 xasprintf(&identname, "tinc.%s", netname);
505 identname = xstrdup("tinc");
510 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
511 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
514 xasprintf(&confbase, "%s/%s", installdir, netname);
516 xasprintf(&confbase, "%s", installdir);
521 xasprintf(&logfilename, "%s/tinc.log", confbase);
535 xasprintf(&pidfilename, RUNSTATEDIR "/%s.pid", identname);
539 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
544 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
546 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
550 xasprintf(&confbase, CONFDIR "/tinc");
555 static void free_names() {
563 static bool drop_privs() {
567 logger(LOG_ERR, "%s not supported on this platform", "-U");
572 logger(LOG_ERR, "%s not supported on this platform", "-R");
580 struct passwd *pw = getpwnam(switchuser);
583 logger(LOG_ERR, "unknown user `%s'", switchuser);
589 if(initgroups(switchuser, pw->pw_gid) != 0 ||
590 setgid(pw->pw_gid) != 0) {
591 logger(LOG_ERR, "System call `%s' failed: %s",
592 "initgroups", strerror(errno));
597 // Not supported in android NDK
604 tzset(); /* for proper timestamps in logs */
606 if(chroot(confbase) != 0 || chdir("/") != 0) {
607 logger(LOG_ERR, "System call `%s' failed: %s",
608 "chroot", strerror(errno));
613 confbase = xstrdup("");
617 if(setuid(uid) != 0) {
618 logger(LOG_ERR, "System call `%s' failed: %s",
619 "setuid", strerror(errno));
628 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
630 # define NORMAL_PRIORITY_CLASS 0
631 # define BELOW_NORMAL_PRIORITY_CLASS 10
632 # define HIGH_PRIORITY_CLASS -10
633 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
636 int main(int argc, char **argv) {
637 program_name = argv[0];
639 if(!parse_options(argc, argv)) {
644 printf("%s version %s\n", PACKAGE, VERSION);
645 printf("Copyright (C) 1998-2019 Ivo Timmermans, Guus Sliepen and others.\n"
646 "See the AUTHORS file for a complete list.\n\n"
647 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
648 "and you are welcome to redistribute it under certain conditions;\n"
649 "see the file COPYING for details.\n");
662 return !kill_other(kill_tincd);
665 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
669 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
674 unsetenv("LISTEN_PID");
677 init_configuration(&config_tree);
679 ENGINE_load_builtin_engines();
682 read_server_config();
683 return !keygen(generate_keys);
686 if(!read_server_config()) {
692 if(lzo_init() != LZO_E_OK) {
693 logger(LOG_ERR, "Error initializing LZO compressor!");
701 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
702 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
706 if(!do_detach || !init_service()) {
707 return main2(argc, argv);
713 int main2(int argc, char **argv) {
714 InitializeCriticalSection(&mutex);
715 EnterCriticalSection(&mutex);
717 char *priority = NULL;
725 /* Lock all pages into memory if requested.
726 * This has to be done after daemon()/fork() so it works for child.
727 * No need to do that in parent as it's very short-lived. */
728 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
729 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
736 /* Setup sockets and open device. */
738 if(!setup_network()) {
742 /* Initiate all outgoing connections. */
744 try_outgoing_connections();
746 /* Change process priority */
748 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
749 if(!strcasecmp(priority, "Normal")) {
750 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
751 logger(LOG_ERR, "System call `%s' failed: %s",
752 "setpriority", strerror(errno));
755 } else if(!strcasecmp(priority, "Low")) {
756 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
757 logger(LOG_ERR, "System call `%s' failed: %s",
758 "setpriority", strerror(errno));
761 } else if(!strcasecmp(priority, "High")) {
762 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
763 logger(LOG_ERR, "System call `%s' failed: %s",
764 "setpriority", strerror(errno));
768 logger(LOG_ERR, "Invalid priority `%s`!", priority);
773 /* drop privileges */
778 /* Start main loop. It only exits when tinc is killed. */
780 status = main_loop();
782 /* Shutdown properly. */
787 close_network_connections();
790 logger(LOG_NOTICE, "Terminating");
793 remove_pid(pidfilename);
798 exit_configuration(&config_tree);
799 list_delete_list(cmdline_conf);