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
62 /* If nonzero, display usage information and exit. */
63 static bool show_help = false;
65 /* If nonzero, print the version on standard output and exit. */
66 static bool show_version = false;
69 /* If nonzero, disable swapping for this process. */
70 static bool do_mlock = false;
74 /* If nonzero, chroot to netdir after startup. */
75 static bool do_chroot = false;
77 /* If !NULL, do setuid to given user after startup */
78 static const char *switchuser = NULL;
81 char **g_argv; /* a copy of the cmdline arguments */
83 static int status = 1;
85 typedef enum option_t {
90 OPT_CONFIG_FILE = 'c',
96 OPT_CHANGE_USER = 'U',
108 static struct option const long_options[] = {
109 {"config", required_argument, NULL, OPT_CONFIG_FILE},
110 {"net", required_argument, NULL, OPT_NETNAME},
111 {"no-detach", no_argument, NULL, OPT_NO_DETACH},
112 {"debug", optional_argument, NULL, OPT_DEBUG},
113 {"mlock", no_argument, NULL, OPT_MLOCK},
114 {"chroot", no_argument, NULL, OPT_CHROOT},
115 {"user", required_argument, NULL, OPT_CHANGE_USER},
116 {"syslog", no_argument, NULL, OPT_SYSLOG},
117 {"option", required_argument, NULL, OPT_OPTION},
118 {"help", no_argument, NULL, OPT_HELP},
119 {"version", no_argument, NULL, OPT_VERSION},
120 {"bypass-security", no_argument, NULL, OPT_NO_SECURITY},
121 {"logfile", optional_argument, NULL, OPT_LOGFILE},
122 {"pidfile", required_argument, NULL, OPT_PIDFILE},
127 static struct WSAData wsa_state;
128 int main2(int argc, char **argv);
131 static void usage(bool status) {
133 fprintf(stderr, "Try `%s --help\' for more information.\n",
137 "Usage: %s [option]...\n"
139 " -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 " -n, --net=NETNAME Connect to net NETNAME.\n"
144 " -L, --mlock Lock tinc into main memory.\n"
146 " --logfile[=FILENAME] Write log entries to a logfile.\n"
147 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
148 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
149 " --bypass-security Disables meta protocol security, for debugging.\n"
150 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
152 " -R, --chroot chroot to NET dir at startup.\n"
153 " -U, --user=USER setuid to given USER at startup.\n"
155 " --help Display this help and exit.\n"
156 " --version Output version information and exit.\n"
158 "Report bugs to tinc@tinc-vpn.org.\n",
163 // Try to resolve path to absolute, return a copy of the argument if this fails.
164 static char *get_path_arg(char *arg) {
165 char *result = absolute_path(arg);
168 result = xstrdup(arg);
174 static bool parse_options(int argc, char **argv) {
177 int option_index = 0;
180 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
181 switch((option_t) r) {
182 case OPT_LONG_OPTION:
189 case OPT_CONFIG_FILE:
192 confbase = get_path_arg(optarg);
199 case OPT_MLOCK: /* lock tincd into RAM */
200 #ifndef HAVE_MLOCKALL
201 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
208 case OPT_DEBUG: /* increase debug level */
209 if(!optarg && optind < argc && *argv[optind] != '-') {
210 optarg = argv[optind++];
214 debug_level = atoi(optarg);
224 netname = xstrdup(optarg);
233 cfg = parse_config_line(optarg, NULL, ++lineno);
239 list_insert_tail(&cmdline_conf, cfg);
244 case OPT_CHANGE_USER:
246 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
254 case OPT_CHANGE_USER:
267 case OPT_NO_SECURITY:
268 bypass_security = true;
275 if(!optarg && optind < argc && *argv[optind] != '-') {
276 optarg = argv[optind++];
281 logfilename = get_path_arg(optarg);
289 pidfilename = get_path_arg(optarg);
298 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
303 if(!netname && (netname = getenv("NETNAME"))) {
304 netname = xstrdup(netname);
307 /* netname "." is special: a "top-level name" */
309 if(netname && (!*netname || !strcmp(netname, "."))) {
314 if(netname && !check_netname(netname, false)) {
315 fprintf(stderr, "Invalid character in netname!\n");
319 if(netname && !check_netname(netname, true)) {
320 fprintf(stderr, "Warning: unsafe character in netname!\n");
327 list_empty_list(&cmdline_conf);
331 static bool read_sandbox_level(void) {
332 sandbox_level_t level;
335 if(get_config_string(lookup_config(&config_tree, "Sandbox"), &value)) {
336 if(!strcasecmp("off", value)) {
337 level = SANDBOX_NONE;
338 } else if(!strcasecmp("normal", value)) {
339 level = SANDBOX_NORMAL;
340 } else if(!strcasecmp("high", value)) {
341 level = SANDBOX_HIGH;
343 logger(DEBUG_ALWAYS, LOG_ERR, "Bad sandbox value %s!", value);
351 level = SANDBOX_NORMAL;
353 level = SANDBOX_NONE;
359 if(level > SANDBOX_NONE) {
360 logger(DEBUG_ALWAYS, LOG_ERR, "Sandbox is used but is not supported on this platform");
365 sandbox_set_level(level);
369 static bool drop_privs(void) {
374 struct passwd *pw = getpwnam(switchuser);
377 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
383 // The second parameter to initgroups on macOS requires int,
384 // but __gid_t is unsigned int. There's not much we can do here.
385 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
386 setgid(pw->pw_gid) != 0) {
387 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
388 "initgroups", strerror(errno));
393 // Not supported in android NDK
400 tzset(); /* for proper timestamps in logs */
402 if(chroot(confbase) != 0 || chdir("/") != 0) {
403 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
404 "chroot", strerror(errno));
409 confbase = xstrdup("");
413 if(setuid(uid) != 0) {
414 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
415 "setuid", strerror(errno));
419 #endif // HAVE_WINDOWS
421 makedirs(DIR_CACHE | DIR_HOSTS | DIR_INVITATIONS);
423 return sandbox_enter();
427 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
429 static void stop_handler(void *data, int flags) {
436 static BOOL WINAPI console_ctrl_handler(DWORD type) {
439 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
441 if(WSASetEvent(stop_io.event) == FALSE) {
448 # define NORMAL_PRIORITY_CLASS 0
449 # define BELOW_NORMAL_PRIORITY_CLASS 10
450 # define HIGH_PRIORITY_CLASS -10
451 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
454 static void cleanup(void) {
455 splay_empty_tree(&config_tree);
456 list_empty_list(&cmdline_conf);
460 int main(int argc, char **argv) {
461 program_name = argv[0];
463 if(!parse_options(argc, argv)) {
469 "%s version %s (built %s %s, protocol %d.%d)\n"
474 #ifdef HAVE_LIBGCRYPT
486 #ifndef DISABLE_LEGACY
489 #ifdef ENABLE_JUMBOGRAMS
495 #ifdef HAVE_MINIUPNPC
508 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
509 "See the AUTHORS file for a complete list.\n"
511 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
512 "and you are welcome to redistribute it under certain conditions;\n"
513 "see the file COPYING for details.\n",
514 PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
526 if(chdir(confbase) == -1) {
527 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
533 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
534 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
539 // Check if we got an umbilical fd from the process that started us
540 char *umbstr = getenv("TINC_UMBILICAL");
544 sscanf(umbstr, "%d %d", &umbilical, &colorize);
545 umbilical_colorize = colorize;
547 if(fcntl(umbilical, F_GETFL) < 0) {
554 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
562 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
566 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
571 unsetenv("LISTEN_PID");
574 gettimeofday(&now, NULL);
579 if(!read_server_config(&config_tree)) {
583 if(!read_sandbox_level()) {
587 if(debug_level == DEBUG_NOTHING) {
590 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
597 if(lzo_init() != LZO_E_OK) {
598 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
605 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
607 if(stop_io.event == FALSE) {
613 if(!do_detach || !init_service()) {
614 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
615 result = main2(argc, argv);
620 if(WSACloseEvent(stop_io.event) == FALSE) {
628 int main2(int argc, char **argv) {
632 char *priority = NULL;
640 /* Lock all pages into memory if requested.
641 * This has to be done after daemon()/fork() so it works for child.
642 * No need to do that in parent as it's very short-lived. */
643 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
644 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
651 /* Setup sockets and open device. */
653 if(!setup_network()) {
657 /* Change process priority */
659 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
660 if(!strcasecmp(priority, "Normal")) {
661 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
662 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
665 } else if(!strcasecmp(priority, "Low")) {
666 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
667 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
670 } else if(!strcasecmp(priority, "High")) {
671 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
672 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
676 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
681 /* drop privileges */
686 /* Start main loop. It only exits when tinc is killed. */
688 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
690 if(umbilical) { // snip!
691 if(write(umbilical, "", 1) != 1) {
692 // Pipe full or broken, nothing we can do about it.
699 try_outgoing_connections();
705 status = main_loop();
711 /* Shutdown properly. */
714 close_network_connections();
716 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");