2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2022 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
58 /* If nonzero, display usage information and exit. */
59 static bool show_help = false;
61 /* If nonzero, print the version on standard output and exit. */
62 static bool show_version = false;
64 /* If nonzero, use null ciphers and skip all key exchanges. */
65 bool bypass_security = false;
68 /* If nonzero, disable swapping for this process. */
69 static bool do_mlock = false;
73 /* If nonzero, chroot to netdir after startup. */
74 static bool do_chroot = false;
76 /* If !NULL, do setuid to given user after startup */
77 static const char *switchuser = NULL;
80 /* If nonzero, write log entries to a separate file. */
81 bool use_logfile = false;
83 /* If nonzero, use syslog instead of stderr in no-detach mode. */
84 bool use_syslog = false;
86 char **g_argv; /* a copy of the cmdline arguments */
88 static int status = 1;
90 static struct option const long_options[] = {
91 {"config", required_argument, NULL, 'c'},
92 {"net", required_argument, NULL, 'n'},
93 {"help", no_argument, NULL, 1},
94 {"version", no_argument, NULL, 2},
95 {"no-detach", no_argument, NULL, 'D'},
96 {"debug", optional_argument, NULL, 'd'},
97 {"bypass-security", no_argument, NULL, 3},
98 {"mlock", no_argument, NULL, 'L'},
99 {"chroot", no_argument, NULL, 'R'},
100 {"user", required_argument, NULL, 'U'},
101 {"logfile", optional_argument, NULL, 4},
102 {"syslog", no_argument, NULL, 's'},
103 {"pidfile", required_argument, NULL, 5},
104 {"option", required_argument, NULL, 'o'},
109 static struct WSAData wsa_state;
110 int main2(int argc, char **argv);
113 static void usage(bool status) {
115 fprintf(stderr, "Try `%s --help\' for more information.\n",
118 static const char *message =
119 "Usage: %s [option]...\n"
121 " -c, --config=DIR Read configuration options from DIR.\n"
122 " -D, --no-detach Don't fork and detach.\n"
123 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
124 " -n, --net=NETNAME Connect to net NETNAME.\n"
126 " -L, --mlock Lock tinc into main memory.\n"
128 " --logfile[=FILENAME] Write log entries to a logfile.\n"
129 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
130 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
131 " --bypass-security Disables meta protocol security, for debugging.\n"
132 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
134 " -R, --chroot chroot to NET dir at startup.\n"
135 " -U, --user=USER setuid to given USER at startup.\n"
137 " --help Display this help and exit.\n"
138 " --version Output version information and exit.\n"
140 "Report bugs to tinc@tinc-vpn.org.\n";
142 printf(message, program_name);
146 static bool parse_options(int argc, char **argv) {
149 int option_index = 0;
152 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
154 case 0: /* long option */
157 case 'c': /* config file */
159 confbase = xstrdup(optarg);
162 case 'D': /* no detach */
166 case 'L': /* no detach */
167 #ifndef HAVE_MLOCKALL
168 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
175 case 'd': /* increase debug level */
176 if(!optarg && optind < argc && *argv[optind] != '-') {
177 optarg = argv[optind++];
181 debug_level = atoi(optarg);
188 case 'n': /* net name given */
190 netname = xstrdup(optarg);
193 case 's': /* syslog */
198 case 'o': /* option */
199 cfg = parse_config_line(optarg, NULL, ++lineno);
205 list_insert_tail(&cmdline_conf, cfg);
212 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
216 case 'R': /* chroot to NETNAME dir */
220 case 'U': /* setuid to USER */
225 case 1: /* show help */
229 case 2: /* show version */
233 case 3: /* bypass security */
234 bypass_security = true;
237 case 4: /* write log entries to a file */
241 if(!optarg && optind < argc && *argv[optind] != '-') {
242 optarg = argv[optind++];
247 logfilename = xstrdup(optarg);
252 case 5: /* open control socket here */
254 pidfilename = xstrdup(optarg);
257 case '?': /* wrong options */
267 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
272 if(!netname && (netname = getenv("NETNAME"))) {
273 netname = xstrdup(netname);
276 /* netname "." is special: a "top-level name" */
278 if(netname && (!*netname || !strcmp(netname, "."))) {
283 if(netname && !check_netname(netname, false)) {
284 fprintf(stderr, "Invalid character in netname!\n");
288 if(netname && !check_netname(netname, true)) {
289 fprintf(stderr, "Warning: unsafe character in netname!\n");
296 list_empty_list(&cmdline_conf);
300 static bool drop_privs(void) {
305 struct passwd *pw = getpwnam(switchuser);
308 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
314 // The second parameter to initgroups on macOS requires int,
315 // but __gid_t is unsigned int. There's not much we can do here.
316 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
317 setgid(pw->pw_gid) != 0) {
318 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
319 "initgroups", strerror(errno));
324 // Not supported in android NDK
331 tzset(); /* for proper timestamps in logs */
333 if(chroot(confbase) != 0 || chdir("/") != 0) {
334 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
335 "chroot", strerror(errno));
340 confbase = xstrdup("");
344 if(setuid(uid) != 0) {
345 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
346 "setuid", strerror(errno));
355 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
357 static void stop_handler(void *data, int flags) {
364 static BOOL WINAPI console_ctrl_handler(DWORD type) {
367 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
369 if(WSASetEvent(stop_io.event) == FALSE) {
376 # define NORMAL_PRIORITY_CLASS 0
377 # define BELOW_NORMAL_PRIORITY_CLASS 10
378 # define HIGH_PRIORITY_CLASS -10
379 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
382 static void cleanup(void) {
383 splay_empty_tree(&config_tree);
384 list_empty_list(&cmdline_conf);
388 int main(int argc, char **argv) {
389 program_name = argv[0];
391 if(!parse_options(argc, argv)) {
396 static const char *message =
397 "%s version %s (built %s %s, protocol %d.%d)\n"
402 #ifdef HAVE_LIBGCRYPT
414 #ifndef DISABLE_LEGACY
417 #ifdef ENABLE_JUMBOGRAMS
423 #ifdef HAVE_MINIUPNPC
433 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
434 "See the AUTHORS file for a complete list.\n"
436 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
437 "and you are welcome to redistribute it under certain conditions;\n"
438 "see the file COPYING for details.\n";
440 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
452 if(chdir(confbase) == -1) {
453 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
459 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
460 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
465 // Check if we got an umbilical fd from the process that started us
466 char *umbstr = getenv("TINC_UMBILICAL");
469 umbilical = atoi(umbstr);
471 if(fcntl(umbilical, F_GETFL) < 0) {
478 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
486 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
490 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
495 unsetenv("LISTEN_PID");
498 gettimeofday(&now, NULL);
502 if(!read_server_config(&config_tree)) {
506 if(debug_level == DEBUG_NOTHING) {
509 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
516 if(lzo_init() != LZO_E_OK) {
517 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
524 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
526 if(stop_io.event == FALSE) {
532 if(!do_detach || !init_service()) {
533 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
534 result = main2(argc, argv);
539 if(WSACloseEvent(stop_io.event) == FALSE) {
547 int main2(int argc, char **argv) {
551 char *priority = NULL;
559 /* Lock all pages into memory if requested.
560 * This has to be done after daemon()/fork() so it works for child.
561 * No need to do that in parent as it's very short-lived. */
562 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
563 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
570 /* Setup sockets and open device. */
572 if(!setup_network()) {
576 /* Change process priority */
578 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
579 if(!strcasecmp(priority, "Normal")) {
580 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
581 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
584 } else if(!strcasecmp(priority, "Low")) {
585 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
586 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
589 } else if(!strcasecmp(priority, "High")) {
590 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
591 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
595 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
600 /* drop privileges */
605 /* Start main loop. It only exits when tinc is killed. */
607 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
609 if(umbilical) { // snip!
610 if(write(umbilical, "", 1) != 1) {
611 // Pipe full or broken, nothing we can do about it.
618 try_outgoing_connections();
620 status = main_loop();
622 /* Shutdown properly. */
625 close_network_connections();
627 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");