2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2013 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>
65 /* The name this program was run with. */
66 char *program_name = NULL;
68 /* If nonzero, display usage information and exit. */
69 bool show_help = false;
71 /* If nonzero, print the version on standard output and exit. */
72 bool show_version = false;
74 /* If nonzero, it will attempt to kill a running tincd and exit. */
77 /* If nonzero, generate public/private keypair for this host/net. */
78 int generate_keys = 0;
80 /* If nonzero, use null ciphers and skip all key exchanges. */
81 bool bypass_security = false;
83 /* If nonzero, disable swapping for this process. */
84 bool do_mlock = false;
86 /* If nonzero, chroot to netdir after startup. */
87 static bool do_chroot = false;
89 /* If !NULL, do setuid to given user after startup */
90 static const char *switchuser = NULL;
92 /* If nonzero, write log entries to a separate file. */
93 bool use_logfile = false;
95 char *identname = NULL; /* program name for syslog */
96 char *pidfilename = NULL; /* pid file location */
97 char *logfilename = NULL; /* log file location */
98 char **g_argv; /* a copy of the cmdline arguments */
102 static struct option const long_options[] = {
103 {"config", required_argument, NULL, 'c'},
104 {"kill", optional_argument, NULL, 'k'},
105 {"net", required_argument, NULL, 'n'},
106 {"help", no_argument, NULL, 1},
107 {"version", no_argument, NULL, 2},
108 {"no-detach", no_argument, NULL, 'D'},
109 {"generate-keys", optional_argument, NULL, 'K'},
110 {"debug", optional_argument, NULL, 'd'},
111 {"bypass-security", no_argument, NULL, 3},
112 {"mlock", no_argument, NULL, 'L'},
113 {"chroot", no_argument, NULL, 'R'},
114 {"user", required_argument, NULL, 'U'},
115 {"logfile", optional_argument, NULL, 4},
116 {"pidfile", required_argument, NULL, 5},
117 {"option", required_argument, NULL, 'o'},
122 static struct WSAData wsa_state;
123 CRITICAL_SECTION mutex;
124 int main2(int argc, char **argv);
127 static void usage(bool status) {
129 fprintf(stderr, "Try `%s --help\' for more information.\n",
132 printf("Usage: %s [option]...\n\n", program_name);
133 printf(" -c, --config=DIR Read configuration options from DIR.\n"
134 " -D, --no-detach Don't fork and detach.\n"
135 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
136 " -k, --kill[=SIGNAL] Attempt to kill a running tincd and exit.\n"
137 " -n, --net=NETNAME Connect to net NETNAME.\n"
138 " -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
139 " -L, --mlock Lock tinc into main memory.\n"
140 " --logfile[=FILENAME] Write log entries to a logfile.\n"
141 " --pidfile=FILENAME Write PID to FILENAME.\n"
142 " -o, --option=[HOST.]KEY=VALUE Set global/host configuration value.\n"
143 " -R, --chroot chroot to NET dir at startup.\n"
144 " -U, --user=USER setuid to given USER at startup.\n"
145 " --help Display this help and exit.\n"
146 " --version Output version information and exit.\n\n");
147 printf("Report bugs to tinc@tinc-vpn.org.\n");
151 static bool parse_options(int argc, char **argv) {
154 int option_index = 0;
157 cmdline_conf = list_alloc((list_action_t)free_config);
159 while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
161 case 0: /* long option */
164 case 'c': /* config file */
165 confbase = xstrdup(optarg);
168 case 'D': /* no detach */
172 case 'L': /* no detach */
173 #ifndef HAVE_MLOCKALL
174 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
181 case 'd': /* increase debug level */
182 if(!optarg && optind < argc && *argv[optind] != '-')
183 optarg = argv[optind++];
185 debug_level = atoi(optarg);
190 case 'k': /* kill old tincds */
192 if(!optarg && optind < argc && *argv[optind] != '-')
193 optarg = argv[optind++];
195 if(!strcasecmp(optarg, "HUP"))
197 else if(!strcasecmp(optarg, "TERM"))
198 kill_tincd = SIGTERM;
199 else if(!strcasecmp(optarg, "KILL"))
200 kill_tincd = SIGKILL;
201 else if(!strcasecmp(optarg, "USR1"))
202 kill_tincd = SIGUSR1;
203 else if(!strcasecmp(optarg, "USR2"))
204 kill_tincd = SIGUSR2;
205 else if(!strcasecmp(optarg, "WINCH"))
206 kill_tincd = SIGWINCH;
207 else if(!strcasecmp(optarg, "INT"))
209 else if(!strcasecmp(optarg, "ALRM"))
210 kill_tincd = SIGALRM;
211 else if(!strcasecmp(optarg, "ABRT"))
212 kill_tincd = SIGABRT;
214 kill_tincd = atoi(optarg);
217 fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
224 kill_tincd = SIGTERM;
230 case 'n': /* net name given */
231 /* netname "." is special: a "top-level name" */
232 netname = strcmp(optarg, ".") != 0 ? xstrdup(optarg) : NULL;
235 case 'o': /* option */
236 cfg = parse_config_line(optarg, NULL, ++lineno);
239 list_insert_tail(cmdline_conf, cfg);
242 case 'K': /* generate public/private keypair */
243 if(!optarg && optind < argc && *argv[optind] != '-')
244 optarg = argv[optind++];
246 generate_keys = atoi(optarg);
248 if(generate_keys < 512) {
249 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
255 generate_keys &= ~7; /* Round it to bytes */
257 generate_keys = 2048;
260 case 'R': /* chroot to NETNAME dir */
264 case 'U': /* setuid to USER */
268 case 1: /* show help */
272 case 2: /* show version */
276 case 3: /* bypass security */
277 bypass_security = true;
280 case 4: /* write log entries to a file */
282 if(!optarg && optind < argc && *argv[optind] != '-')
283 optarg = argv[optind++];
285 logfilename = xstrdup(optarg);
288 case 5: /* write PID to a file */
289 pidfilename = xstrdup(optarg);
302 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
310 /* This function prettyprints the key generation process */
312 static void indicator(int a, int b, void *p) {
315 fprintf(stderr, ".");
319 fprintf(stderr, "+");
323 fprintf(stderr, "-");
329 fprintf(stderr, " p\n");
333 fprintf(stderr, " q\n");
337 fprintf(stderr, "?");
342 fprintf(stderr, "?");
347 Generate a public/private RSA keypair, and ask for a file to store
350 static bool keygen(int bits) {
353 char *name = get_name();
354 char *pubname, *privname;
356 fprintf(stderr, "Generating %d bits keys:\n", bits);
357 rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
360 fprintf(stderr, "Error during key generation!\n");
363 fprintf(stderr, "Done.\n");
365 xasprintf(&privname, "%s/rsa_key.priv", confbase);
366 f = ask_and_open(privname, "private RSA key");
373 /* Make it unreadable for others. */
374 fchmod(fileno(f), 0600);
378 PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
382 xasprintf(&pubname, "%s/hosts/%s", confbase, name);
384 xasprintf(&pubname, "%s/rsa_key.pub", confbase);
386 f = ask_and_open(pubname, "public RSA key");
393 PEM_write_RSAPublicKey(f, rsa_key);
401 Set all files and paths according to netname
403 static void make_names(void) {
406 char installdir[1024] = "";
407 DWORD len = sizeof(installdir);
411 xasprintf(&identname, "tinc.%s", netname);
413 identname = xstrdup("tinc");
416 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
417 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
419 xasprintf(&logfilename, "%s/log/%s.log", identname);
422 xasprintf(&confbase, "%s/%s", installdir, netname);
424 xasprintf(&confbase, "%s", installdir);
434 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
437 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
441 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
443 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
446 xasprintf(&confbase, CONFDIR "/tinc");
450 static void free_names() {
451 if (identname) free(identname);
452 if (netname) free(netname);
453 if (pidfilename) free(pidfilename);
454 if (logfilename) free(logfilename);
455 if (confbase) free(confbase);
458 static bool drop_privs() {
461 logger(LOG_ERR, "%s not supported on this platform", "-U");
465 logger(LOG_ERR, "%s not supported on this platform", "-R");
471 struct passwd *pw = getpwnam(switchuser);
473 logger(LOG_ERR, "unknown user `%s'", switchuser);
477 if (initgroups(switchuser, pw->pw_gid) != 0 ||
478 setgid(pw->pw_gid) != 0) {
479 logger(LOG_ERR, "System call `%s' failed: %s",
480 "initgroups", strerror(errno));
484 // Not supported in android NDK
490 tzset(); /* for proper timestamps in logs */
491 if (chroot(confbase) != 0 || chdir("/") != 0) {
492 logger(LOG_ERR, "System call `%s' failed: %s",
493 "chroot", strerror(errno));
497 confbase = xstrdup("");
500 if (setuid(uid) != 0) {
501 logger(LOG_ERR, "System call `%s' failed: %s",
502 "setuid", strerror(errno));
510 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
512 # define NORMAL_PRIORITY_CLASS 0
513 # define BELOW_NORMAL_PRIORITY_CLASS 10
514 # define HIGH_PRIORITY_CLASS -10
515 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
518 int main(int argc, char **argv) {
519 program_name = argv[0];
521 if(!parse_options(argc, argv))
527 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
528 VERSION, __DATE__, __TIME__, PROT_CURRENT);
529 printf("Copyright (C) 1998-2013 Ivo Timmermans, Guus Sliepen and others.\n"
530 "See the AUTHORS file for a complete list.\n\n"
531 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
532 "and you are welcome to redistribute it under certain conditions;\n"
533 "see the file COPYING for details.\n");
544 return !kill_other(kill_tincd);
546 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
550 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
553 unsetenv("LISTEN_PID");
556 init_configuration(&config_tree);
558 /* Slllluuuuuuurrrrp! */
560 RAND_load_file("/dev/urandom", 1024);
562 ENGINE_load_builtin_engines();
563 ENGINE_register_all_complete();
565 OpenSSL_add_all_algorithms();
568 read_server_config();
569 return !keygen(generate_keys);
572 if(!read_server_config())
576 if(lzo_init() != LZO_E_OK) {
577 logger(LOG_ERR, "Error initializing LZO compressor!");
583 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
584 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
588 if(!do_detach || !init_service())
589 return main2(argc, argv);
594 int main2(int argc, char **argv) {
595 InitializeCriticalSection(&mutex);
596 EnterCriticalSection(&mutex);
598 char *priority = NULL;
604 /* Lock all pages into memory if requested.
605 * This has to be done after daemon()/fork() so it works for child.
606 * No need to do that in parent as it's very short-lived. */
607 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
608 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
614 /* Setup sockets and open device. */
619 /* Initiate all outgoing connections. */
621 try_outgoing_connections();
623 /* Change process priority */
625 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
626 if(!strcasecmp(priority, "Normal")) {
627 if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
628 logger(LOG_ERR, "System call `%s' failed: %s",
629 "setpriority", strerror(errno));
632 } else if(!strcasecmp(priority, "Low")) {
633 if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
634 logger(LOG_ERR, "System call `%s' failed: %s",
635 "setpriority", strerror(errno));
638 } else if(!strcasecmp(priority, "High")) {
639 if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
640 logger(LOG_ERR, "System call `%s' failed: %s",
641 "setpriority", strerror(errno));
645 logger(LOG_ERR, "Invalid priority `%s`!", priority);
650 /* drop privileges */
654 /* Start main loop. It only exits when tinc is killed. */
656 status = main_loop();
658 /* Shutdown properly. */
663 close_network_connections();
666 logger(LOG_NOTICE, "Terminating");
669 remove_pid(pidfilename);
676 CRYPTO_cleanup_all_ex_data();
680 exit_configuration(&config_tree);
681 list_free(cmdline_conf);