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>
54 #ifdef HAVE_GETOPT_LONG
72 /* The name this program was run with. */
73 char *program_name = NULL;
75 /* If nonzero, display usage information and exit. */
76 bool show_help = false;
78 /* If nonzero, print the version on standard output and exit. */
79 bool show_version = false;
81 /* If nonzero, it will attempt to kill a running tincd and exit. */
84 /* If nonzero, generate public/private keypair for this host/net. */
85 int generate_keys = 0;
87 /* If nonzero, use null ciphers and skip all key exchanges. */
88 bool bypass_security = false;
90 /* If nonzero, disable swapping for this process. */
91 bool do_mlock = false;
93 /* If nonzero, chroot to netdir after startup. */
94 static bool do_chroot = false;
96 /* If !NULL, do setuid to given user after startup */
97 static const char *switchuser = NULL;
99 /* If nonzero, write log entries to a separate file. */
100 bool use_logfile = false;
102 char *identname = NULL; /* program name for syslog */
103 char *pidfilename = NULL; /* pid file location */
104 char *logfilename = NULL; /* log file location */
105 char **g_argv; /* a copy of the cmdline arguments */
107 static int status = 1;
109 static struct option const long_options[] = {
110 {"config", required_argument, NULL, 'c'},
111 {"kill", optional_argument, NULL, 'k'},
112 {"net", required_argument, NULL, 'n'},
113 {"help", no_argument, NULL, 1},
114 {"version", no_argument, NULL, 2},
115 {"no-detach", no_argument, NULL, 'D'},
116 {"generate-keys", optional_argument, NULL, 'K'},
117 {"debug", optional_argument, NULL, 'd'},
118 {"bypass-security", no_argument, NULL, 3},
119 {"mlock", no_argument, NULL, 'L'},
120 {"chroot", no_argument, NULL, 'R'},
121 {"user", required_argument, NULL, 'U'},
122 {"logfile", optional_argument, NULL, 4},
123 {"pidfile", required_argument, NULL, 5},
124 {"option", required_argument, NULL, 'o'},
129 static struct WSAData wsa_state;
130 CRITICAL_SECTION mutex;
131 int main2(int argc, char **argv);
134 static void usage(bool status) {
136 fprintf(stderr, "Try `%s --help\' for more information.\n",
139 printf("Usage: %s [option]...\n\n", program_name);
140 printf(" -c, --config=DIR Read configuration options from DIR.\n"
141 " -D, --no-detach Don't fork and detach.\n"
142 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
143 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
144 " -n, --net=NETNAME Connect to net NETNAME.\n"
145 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
146 " -L, --mlock Lock tinc into main memory.\n"
147 " --logfile[=FILENAME] Write log entries to a logfile.\n"
148 " --pidfile=FILENAME Write PID to FILENAME.\n"
149 " -o, --option=[HOST.]KEY=VALUE Set global/host configuration value.\n"
150 " -R, --chroot chroot to NET dir at startup.\n"
151 " -U, --user=USER setuid to given USER at startup.\n"
152 " --help Display this help and exit.\n"
153 " --version Output version information and exit.\n\n");
154 printf("Report bugs to tinc@tinc-vpn.org.\n");
158 static bool parse_options(int argc, char **argv) {
161 int option_index = 0;
164 cmdline_conf = list_alloc((list_action_t)free_config);
166 while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
168 case 0: /* long option */
171 case 'c': /* config file */
173 fprintf(stderr, "Only one configuration directory can be given.\n");
178 confbase = xstrdup(optarg);
181 case 'D': /* no detach */
185 case 'L': /* no detach */
186 #ifndef HAVE_MLOCKALL
187 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
194 case 'd': /* increase debug level */
195 if(!optarg && optind < argc && *argv[optind] != '-') {
196 optarg = argv[optind++];
200 debug_level = atoi(optarg);
207 case 'k': /* kill old tincds */
209 if(!optarg && optind < argc && *argv[optind] != '-') {
210 optarg = argv[optind++];
214 if(!strcasecmp(optarg, "HUP")) {
216 } else if(!strcasecmp(optarg, "TERM")) {
217 kill_tincd = SIGTERM;
218 } else if(!strcasecmp(optarg, "KILL")) {
219 kill_tincd = SIGKILL;
220 } else if(!strcasecmp(optarg, "USR1")) {
221 kill_tincd = SIGUSR1;
222 } else if(!strcasecmp(optarg, "USR2")) {
223 kill_tincd = SIGUSR2;
224 } else if(!strcasecmp(optarg, "WINCH")) {
225 kill_tincd = SIGWINCH;
226 } else if(!strcasecmp(optarg, "INT")) {
228 } else if(!strcasecmp(optarg, "ALRM")) {
229 kill_tincd = SIGALRM;
230 } else if(!strcasecmp(optarg, "ABRT")) {
231 kill_tincd = SIGABRT;
233 kill_tincd = atoi(optarg);
236 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
243 kill_tincd = SIGTERM;
251 case 'n': /* net name given */
253 /* netname "." is special: a "top-level name" */
255 fprintf(stderr, "Only one netname can be given.\n");
260 if(optarg && strcmp(optarg, ".")) {
261 netname = xstrdup(optarg);
266 case 'o': /* option */
267 cfg = parse_config_line(optarg, NULL, ++lineno);
273 list_insert_tail(cmdline_conf, cfg);
276 case 'K': /* generate public/private keypair */
277 if(!optarg && optind < argc && *argv[optind] != '-') {
278 optarg = argv[optind++];
282 generate_keys = atoi(optarg);
284 if(generate_keys < 512) {
285 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
291 generate_keys &= ~7; /* Round it to bytes */
293 generate_keys = 2048;
298 case 'R': /* chroot to NETNAME dir */
302 case 'U': /* setuid to USER */
306 case 1: /* show help */
310 case 2: /* show version */
314 case 3: /* bypass security */
315 bypass_security = true;
318 case 4: /* write log entries to a file */
321 if(!optarg && optind < argc && *argv[optind] != '-') {
322 optarg = argv[optind++];
327 fprintf(stderr, "Only one logfile can be given.\n");
332 logfilename = xstrdup(optarg);
337 case 5: /* write PID to a file */
339 fprintf(stderr, "Only one pidfile can be given.\n");
344 pidfilename = xstrdup(optarg);
357 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
365 /* This function prettyprints the key generation process */
367 static int indicator(int a, int b, BN_GENCB *cb) {
372 fprintf(stderr, ".");
376 fprintf(stderr, "+");
380 fprintf(stderr, "-");
386 fprintf(stderr, " p\n");
390 fprintf(stderr, " q\n");
394 fprintf(stderr, "?");
400 fprintf(stderr, "?");
406 #ifndef HAVE_BN_GENCB_NEW
407 BN_GENCB *BN_GENCB_new(void) {
408 return xmalloc_and_zero(sizeof(BN_GENCB));
411 void BN_GENCB_free(BN_GENCB *cb) {
417 Generate a public/private RSA keypair, and ask for a file to store
420 static bool keygen(int bits) {
424 char filename[PATH_MAX];
428 fprintf(stderr, "Generating %d bits keys:\n", bits);
436 BN_GENCB_set(cb, indicator, NULL);
440 if(BN_hex2bn(&e, "10001") == 0) {
448 result = RSA_generate_key_ex(rsa_key, bits, e, cb);
454 fprintf(stderr, "Error during key generation!\n");
458 fprintf(stderr, "Done.\n");
461 snprintf(filename, sizeof(filename), "%s/rsa_key.priv", confbase);
462 f = ask_and_open(filename, "private RSA key");
470 /* Make it unreadable for others. */
471 fchmod(fileno(f), 0600);
475 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
478 char *name = get_name();
481 snprintf(filename, sizeof(filename), "%s/hosts/%s", confbase, name);
484 snprintf(filename, sizeof(filename), "%s/rsa_key.pub", confbase);
487 f = ask_and_open(filename, "public RSA key");
495 PEM_write_RSAPublicKey(f, rsa_key);
504 Set all files and paths according to netname
506 static void make_names(void) {
509 char installdir[1024] = "";
510 DWORD len = sizeof(installdir);
514 xasprintf(&identname, "tinc.%s", netname);
516 identname = xstrdup("tinc");
521 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
522 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
525 xasprintf(&confbase, "%s/%s", installdir, netname);
527 xasprintf(&confbase, "%s", installdir);
532 xasprintf(&logfilename, "%s/tinc.log", confbase);
546 xasprintf(&pidfilename, RUNSTATEDIR "/%s.pid", identname);
550 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
555 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
557 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
561 xasprintf(&confbase, CONFDIR "/tinc");
566 static void free_names() {
574 static bool drop_privs() {
578 logger(LOG_ERR, "%s not supported on this platform", "-U");
583 logger(LOG_ERR, "%s not supported on this platform", "-R");
591 struct passwd *pw = getpwnam(switchuser);
594 logger(LOG_ERR, "unknown user `%s'", switchuser);
600 if(initgroups(switchuser, pw->pw_gid) != 0 ||
601 setgid(pw->pw_gid) != 0) {
602 logger(LOG_ERR, "System call `%s' failed: %s",
603 "initgroups", strerror(errno));
608 // Not supported in android NDK
615 tzset(); /* for proper timestamps in logs */
617 if(chroot(confbase) != 0 || chdir("/") != 0) {
618 logger(LOG_ERR, "System call `%s' failed: %s",
619 "chroot", strerror(errno));
624 confbase = xstrdup("");
628 if(setuid(uid) != 0) {
629 logger(LOG_ERR, "System call `%s' failed: %s",
630 "setuid", strerror(errno));
639 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
641 # define NORMAL_PRIORITY_CLASS 0
642 # define BELOW_NORMAL_PRIORITY_CLASS 10
643 # define HIGH_PRIORITY_CLASS -10
644 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
647 int main(int argc, char **argv) {
648 program_name = argv[0];
650 if(!parse_options(argc, argv)) {
655 printf("%s version %s\n", PACKAGE, VERSION);
656 printf("Copyright (C) 1998-2018 Ivo Timmermans, Guus Sliepen and others.\n"
657 "See the AUTHORS file for a complete list.\n\n"
658 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
659 "and you are welcome to redistribute it under certain conditions;\n"
660 "see the file COPYING for details.\n");
673 return !kill_other(kill_tincd);
676 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
680 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
685 unsetenv("LISTEN_PID");
688 init_configuration(&config_tree);
690 #ifndef OPENSSL_NO_ENGINE
691 ENGINE_load_builtin_engines();
692 ENGINE_register_all_complete();
695 OpenSSL_add_all_algorithms();
698 read_server_config();
699 return !keygen(generate_keys);
702 if(!read_server_config()) {
708 if(lzo_init() != LZO_E_OK) {
709 logger(LOG_ERR, "Error initializing LZO compressor!");
717 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
718 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
722 if(!do_detach || !init_service()) {
723 return main2(argc, argv);
729 int main2(int argc, char **argv) {
730 InitializeCriticalSection(&mutex);
731 EnterCriticalSection(&mutex);
733 char *priority = NULL;
741 /* Lock all pages into memory if requested.
742 * This has to be done after daemon()/fork() so it works for child.
743 * No need to do that in parent as it's very short-lived. */
744 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
745 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
752 /* Setup sockets and open device. */
754 if(!setup_network()) {
758 /* Initiate all outgoing connections. */
760 try_outgoing_connections();
762 /* Change process priority */
764 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
765 if(!strcasecmp(priority, "Normal")) {
766 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
767 logger(LOG_ERR, "System call `%s' failed: %s",
768 "setpriority", strerror(errno));
771 } else if(!strcasecmp(priority, "Low")) {
772 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
773 logger(LOG_ERR, "System call `%s' failed: %s",
774 "setpriority", strerror(errno));
777 } else if(!strcasecmp(priority, "High")) {
778 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
779 logger(LOG_ERR, "System call `%s' failed: %s",
780 "setpriority", strerror(errno));
784 logger(LOG_ERR, "Invalid priority `%s`!", priority);
789 /* drop privileges */
794 /* Start main loop. It only exits when tinc is killed. */
796 status = main_loop();
798 /* Shutdown properly. */
803 close_network_connections();
806 logger(LOG_NOTICE, "Terminating");
809 remove_pid(pidfilename);
816 #ifndef OPENSSL_NO_ENGINE
820 exit_configuration(&config_tree);
821 list_delete_list(cmdline_conf);