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 #ifndef OPENSSL_NO_ENGINE
41 #include <openssl/engine.h>
43 #include <openssl/bn.h>
55 #ifdef HAVE_GETOPT_LONG
73 /* The name this program was run with. */
74 char *program_name = NULL;
76 /* If nonzero, display usage information and exit. */
77 bool show_help = false;
79 /* If nonzero, print the version on standard output and exit. */
80 bool show_version = false;
82 /* If nonzero, it will attempt to kill a running tincd and exit. */
85 /* If nonzero, generate public/private keypair for this host/net. */
86 int generate_keys = 0;
88 /* If nonzero, use null ciphers and skip all key exchanges. */
89 bool bypass_security = false;
91 /* If nonzero, disable swapping for this process. */
92 bool do_mlock = false;
94 /* If nonzero, chroot to netdir after startup. */
95 static bool do_chroot = false;
97 /* If !NULL, do setuid to given user after startup */
98 static const char *switchuser = NULL;
100 /* If nonzero, write log entries to a separate file. */
101 bool use_logfile = false;
103 char *identname = NULL; /* program name for syslog */
104 char *pidfilename = NULL; /* pid file location */
105 char *logfilename = NULL; /* log file location */
106 char **g_argv; /* a copy of the cmdline arguments */
108 static int status = 1;
110 static struct option const long_options[] = {
111 {"config", required_argument, NULL, 'c'},
112 {"kill", optional_argument, NULL, 'k'},
113 {"net", required_argument, NULL, 'n'},
114 {"help", no_argument, NULL, 1},
115 {"version", no_argument, NULL, 2},
116 {"no-detach", no_argument, NULL, 'D'},
117 {"generate-keys", optional_argument, NULL, 'K'},
118 {"debug", optional_argument, NULL, 'd'},
119 {"bypass-security", no_argument, NULL, 3},
120 {"mlock", no_argument, NULL, 'L'},
121 {"chroot", no_argument, NULL, 'R'},
122 {"user", required_argument, NULL, 'U'},
123 {"logfile", optional_argument, NULL, 4},
124 {"pidfile", required_argument, NULL, 5},
125 {"option", required_argument, NULL, 'o'},
130 static struct WSAData wsa_state;
131 CRITICAL_SECTION mutex;
132 int main2(int argc, char **argv);
135 static void usage(bool status) {
137 fprintf(stderr, "Try `%s --help\' for more information.\n",
140 printf("Usage: %s [option]...\n\n", program_name);
141 printf(" -c, --config=DIR Read configuration options from DIR.\n"
142 " -D, --no-detach Don't fork and detach.\n"
143 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
144 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
145 " -n, --net=NETNAME Connect to net NETNAME.\n"
146 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
147 " -L, --mlock Lock tinc into main memory.\n"
148 " --logfile[=FILENAME] Write log entries to a logfile.\n"
149 " --pidfile=FILENAME Write PID to FILENAME.\n"
150 " -o, --option=[HOST.]KEY=VALUE Set global/host configuration value.\n"
151 " -R, --chroot chroot to NET dir at startup.\n"
152 " -U, --user=USER setuid to given USER at startup.\n"
153 " --help Display this help and exit.\n"
154 " --version Output version information and exit.\n\n");
155 printf("Report bugs to tinc@tinc-vpn.org.\n");
159 static bool parse_options(int argc, char **argv) {
162 int option_index = 0;
165 cmdline_conf = list_alloc((list_action_t)free_config);
167 while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
169 case 0: /* long option */
172 case 'c': /* config file */
174 fprintf(stderr, "Only one configuration directory can be given.\n");
179 confbase = xstrdup(optarg);
182 case 'D': /* no detach */
186 case 'L': /* no detach */
187 #ifndef HAVE_MLOCKALL
188 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
195 case 'd': /* increase debug level */
196 if(!optarg && optind < argc && *argv[optind] != '-') {
197 optarg = argv[optind++];
201 debug_level = atoi(optarg);
208 case 'k': /* kill old tincds */
210 if(!optarg && optind < argc && *argv[optind] != '-') {
211 optarg = argv[optind++];
215 if(!strcasecmp(optarg, "HUP")) {
217 } else if(!strcasecmp(optarg, "TERM")) {
218 kill_tincd = SIGTERM;
219 } else if(!strcasecmp(optarg, "KILL")) {
220 kill_tincd = SIGKILL;
221 } else if(!strcasecmp(optarg, "USR1")) {
222 kill_tincd = SIGUSR1;
223 } else if(!strcasecmp(optarg, "USR2")) {
224 kill_tincd = SIGUSR2;
225 } else if(!strcasecmp(optarg, "WINCH")) {
226 kill_tincd = SIGWINCH;
227 } else if(!strcasecmp(optarg, "INT")) {
229 } else if(!strcasecmp(optarg, "ALRM")) {
230 kill_tincd = SIGALRM;
231 } else if(!strcasecmp(optarg, "ABRT")) {
232 kill_tincd = SIGABRT;
234 kill_tincd = atoi(optarg);
237 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
244 kill_tincd = SIGTERM;
252 case 'n': /* net name given */
254 /* netname "." is special: a "top-level name" */
256 fprintf(stderr, "Only one netname can be given.\n");
261 if(optarg && strcmp(optarg, ".")) {
262 netname = xstrdup(optarg);
267 case 'o': /* option */
268 cfg = parse_config_line(optarg, NULL, ++lineno);
274 list_insert_tail(cmdline_conf, cfg);
277 case 'K': /* generate public/private keypair */
278 if(!optarg && optind < argc && *argv[optind] != '-') {
279 optarg = argv[optind++];
283 generate_keys = atoi(optarg);
285 if(generate_keys < 512) {
286 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
292 generate_keys &= ~7; /* Round it to bytes */
294 generate_keys = 2048;
299 case 'R': /* chroot to NETNAME dir */
303 case 'U': /* setuid to USER */
307 case 1: /* show help */
311 case 2: /* show version */
315 case 3: /* bypass security */
316 bypass_security = true;
319 case 4: /* write log entries to a file */
322 if(!optarg && optind < argc && *argv[optind] != '-') {
323 optarg = argv[optind++];
328 fprintf(stderr, "Only one logfile can be given.\n");
333 logfilename = xstrdup(optarg);
338 case 5: /* write PID to a file */
340 fprintf(stderr, "Only one pidfile can be given.\n");
345 pidfilename = xstrdup(optarg);
358 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
366 /* This function prettyprints the key generation process */
368 static int indicator(int a, int b, BN_GENCB *cb) {
373 fprintf(stderr, ".");
377 fprintf(stderr, "+");
381 fprintf(stderr, "-");
387 fprintf(stderr, " p\n");
391 fprintf(stderr, " q\n");
395 fprintf(stderr, "?");
401 fprintf(stderr, "?");
407 #ifndef HAVE_BN_GENCB_NEW
408 BN_GENCB *BN_GENCB_new(void) {
409 return xmalloc_and_zero(sizeof(BN_GENCB));
412 void BN_GENCB_free(BN_GENCB *cb) {
418 Generate a public/private RSA keypair, and ask for a file to store
421 static bool keygen(int bits) {
425 char filename[PATH_MAX];
429 fprintf(stderr, "Generating %d bits keys:\n", bits);
437 BN_GENCB_set(cb, indicator, NULL);
441 if(BN_hex2bn(&e, "10001") == 0) {
449 result = RSA_generate_key_ex(rsa_key, bits, e, cb);
455 fprintf(stderr, "Error during key generation!\n");
459 fprintf(stderr, "Done.\n");
462 snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
463 f = ask_and_open(filename, "private RSA key");
471 /* Make it unreadable for others. */
472 fchmod(fileno(f), 0600);
476 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
479 char *name = get_name();
482 snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
485 snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
488 f = ask_and_open(filename, "public RSA key");
496 PEM_write_RSAPublicKey(f, rsa_key);
505 Set all files and paths according to netname
507 static void make_names(void) {
510 char installdir[1024] = "";
511 DWORD len = sizeof(installdir);
515 xasprintf(&identname, "tinc.%s", netname);
517 identname = xstrdup("tinc");
522 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
523 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
526 xasprintf(&confbase, "%s/%s", installdir, netname);
528 xasprintf(&confbase, "%s", installdir);
533 xasprintf(&logfilename, "%s/tinc.log", confbase);
547 xasprintf(&pidfilename, RUNSTATEDIR "/%s.pid", identname);
551 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
556 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
558 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
562 xasprintf(&confbase, CONFDIR "/tinc");
567 static void free_names() {
575 static bool drop_privs() {
579 logger(LOG_ERR, "%s not supported on this platform", "-U");
584 logger(LOG_ERR, "%s not supported on this platform", "-R");
592 struct passwd *pw = getpwnam(switchuser);
595 logger(LOG_ERR, "unknown user `%s'", switchuser);
601 if(initgroups(switchuser, pw->pw_gid) != 0 ||
602 setgid(pw->pw_gid) != 0) {
603 logger(LOG_ERR, "System call `%s' failed: %s",
604 "initgroups", strerror(errno));
609 // Not supported in android NDK
616 tzset(); /* for proper timestamps in logs */
618 if(chroot(confbase) != 0 || chdir("/") != 0) {
619 logger(LOG_ERR, "System call `%s' failed: %s",
620 "chroot", strerror(errno));
625 confbase = xstrdup("");
629 if(setuid(uid) != 0) {
630 logger(LOG_ERR, "System call `%s' failed: %s",
631 "setuid", strerror(errno));
640 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
642 # define NORMAL_PRIORITY_CLASS 0
643 # define BELOW_NORMAL_PRIORITY_CLASS 10
644 # define HIGH_PRIORITY_CLASS -10
645 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
648 int main(int argc, char **argv) {
649 program_name = argv[0];
651 if(!parse_options(argc, argv)) {
656 printf("%s version %s\n", PACKAGE, VERSION);
657 printf("Copyright (C) 1998-2018 Ivo Timmermans, Guus Sliepen and others.\n"
658 "See the AUTHORS file for a complete list.\n\n"
659 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
660 "and you are welcome to redistribute it under certain conditions;\n"
661 "see the file COPYING for details.\n");
674 return !kill_other(kill_tincd);
677 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
681 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
686 unsetenv("LISTEN_PID");
689 init_configuration(&config_tree);
691 #ifndef OPENSSL_NO_ENGINE
692 ENGINE_load_builtin_engines();
693 ENGINE_register_all_complete();
696 #if OPENSSL_VERSION_NUMBER < 0x10100000L
697 OpenSSL_add_all_algorithms();
701 read_server_config();
702 return !keygen(generate_keys);
705 if(!read_server_config()) {
711 if(lzo_init() != LZO_E_OK) {
712 logger(LOG_ERR, "Error initializing LZO compressor!");
720 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
721 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
725 if(!do_detach || !init_service()) {
726 return main2(argc, argv);
732 int main2(int argc, char **argv) {
733 InitializeCriticalSection(&mutex);
734 EnterCriticalSection(&mutex);
736 char *priority = NULL;
744 /* Lock all pages into memory if requested.
745 * This has to be done after daemon()/fork() so it works for child.
746 * No need to do that in parent as it's very short-lived. */
747 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
748 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
755 /* Setup sockets and open device. */
757 if(!setup_network()) {
761 /* Initiate all outgoing connections. */
763 try_outgoing_connections();
765 /* Change process priority */
767 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
768 if(!strcasecmp(priority, "Normal")) {
769 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
770 logger(LOG_ERR, "System call `%s' failed: %s",
771 "setpriority", strerror(errno));
774 } else if(!strcasecmp(priority, "Low")) {
775 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
776 logger(LOG_ERR, "System call `%s' failed: %s",
777 "setpriority", strerror(errno));
780 } else if(!strcasecmp(priority, "High")) {
781 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
782 logger(LOG_ERR, "System call `%s' failed: %s",
783 "setpriority", strerror(errno));
787 logger(LOG_ERR, "Invalid priority `%s`!", priority);
792 /* drop privileges */
797 /* Start main loop. It only exits when tinc is killed. */
799 status = main_loop();
801 /* Shutdown properly. */
806 close_network_connections();
809 logger(LOG_NOTICE, "Terminating");
812 remove_pid(pidfilename);
817 #if OPENSSL_VERSION_NUMBER < 0x10100000L
820 #ifndef OPENSSL_NO_ENGINE
825 exit_configuration(&config_tree);
826 list_delete_list(cmdline_conf);