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
60 /* If nonzero, display usage information and exit. */
61 static bool show_help = false;
63 /* If nonzero, print the version on standard output and exit. */
64 static bool show_version = false;
67 /* If nonzero, disable swapping for this process. */
68 static bool do_mlock = false;
72 /* If nonzero, chroot to netdir after startup. */
73 static bool do_chroot = false;
75 /* If !NULL, do setuid to given user after startup */
76 static const char *switchuser = NULL;
79 char **g_argv; /* a copy of the cmdline arguments */
81 static int status = 1;
83 typedef enum option_t {
88 OPT_CONFIG_FILE = 'c',
94 OPT_CHANGE_USER = 'U',
106 static struct option const long_options[] = {
107 {"config", required_argument, NULL, OPT_CONFIG_FILE},
108 {"net", required_argument, NULL, OPT_NETNAME},
109 {"no-detach", no_argument, NULL, OPT_NO_DETACH},
110 {"debug", optional_argument, NULL, OPT_DEBUG},
111 {"mlock", no_argument, NULL, OPT_MLOCK},
112 {"chroot", no_argument, NULL, OPT_CHROOT},
113 {"user", required_argument, NULL, OPT_CHANGE_USER},
114 {"syslog", no_argument, NULL, OPT_SYSLOG},
115 {"option", required_argument, NULL, OPT_OPTION},
116 {"help", no_argument, NULL, OPT_HELP},
117 {"version", no_argument, NULL, OPT_VERSION},
118 {"bypass-security", no_argument, NULL, OPT_NO_SECURITY},
119 {"logfile", optional_argument, NULL, OPT_LOGFILE},
120 {"pidfile", required_argument, NULL, OPT_PIDFILE},
125 static struct WSAData wsa_state;
126 int main2(int argc, char **argv);
129 static void usage(bool status) {
131 fprintf(stderr, "Try `%s --help\' for more information.\n",
135 "Usage: %s [option]...\n"
137 " -c, --config=DIR Read configuration options from DIR.\n"
138 " -D, --no-detach Don't fork and detach.\n"
139 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
140 " -n, --net=NETNAME Connect to net NETNAME.\n"
142 " -L, --mlock Lock tinc into main memory.\n"
144 " --logfile[=FILENAME] Write log entries to a logfile.\n"
145 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
146 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
147 " --bypass-security Disables meta protocol security, for debugging.\n"
148 " -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"
153 " --help Display this help and exit.\n"
154 " --version Output version information and exit.\n"
156 "Report bugs to tinc@tinc-vpn.org.\n",
161 // Try to resolve path to absolute, return a copy of the argument if this fails.
162 static char *get_path_arg(char *arg) {
163 char *result = absolute_path(arg);
166 result = xstrdup(arg);
172 static bool parse_options(int argc, char **argv) {
175 int option_index = 0;
178 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
179 switch((option_t) r) {
180 case OPT_LONG_OPTION:
187 case OPT_CONFIG_FILE:
189 confbase = get_path_arg(optarg);
196 case OPT_MLOCK: /* lock tincd into RAM */
197 #ifndef HAVE_MLOCKALL
198 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
205 case OPT_DEBUG: /* increase debug level */
206 if(!optarg && optind < argc && *argv[optind] != '-') {
207 optarg = argv[optind++];
211 debug_level = atoi(optarg);
220 netname = xstrdup(optarg);
229 cfg = parse_config_line(optarg, NULL, ++lineno);
235 list_insert_tail(&cmdline_conf, cfg);
240 case OPT_CHANGE_USER:
242 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
250 case OPT_CHANGE_USER:
263 case OPT_NO_SECURITY:
264 bypass_security = true;
271 if(!optarg && optind < argc && *argv[optind] != '-') {
272 optarg = argv[optind++];
277 logfilename = get_path_arg(optarg);
284 pidfilename = get_path_arg(optarg);
293 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
298 if(!netname && (netname = getenv("NETNAME"))) {
299 netname = xstrdup(netname);
302 /* netname "." is special: a "top-level name" */
304 if(netname && (!*netname || !strcmp(netname, "."))) {
309 if(netname && !check_netname(netname, false)) {
310 fprintf(stderr, "Invalid character in netname!\n");
314 if(netname && !check_netname(netname, true)) {
315 fprintf(stderr, "Warning: unsafe character in netname!\n");
322 list_empty_list(&cmdline_conf);
326 static bool read_sandbox_level(void) {
327 sandbox_level_t level;
330 if(get_config_string(lookup_config(&config_tree, "Sandbox"), &value)) {
331 if(!strcasecmp("off", value)) {
332 level = SANDBOX_NONE;
333 } else if(!strcasecmp("normal", value)) {
334 level = SANDBOX_NORMAL;
335 } else if(!strcasecmp("high", value)) {
336 level = SANDBOX_HIGH;
338 logger(DEBUG_ALWAYS, LOG_ERR, "Bad sandbox value %s!", value);
346 level = SANDBOX_NORMAL;
348 level = SANDBOX_NONE;
354 if(level > SANDBOX_NONE) {
355 logger(DEBUG_ALWAYS, LOG_ERR, "Sandbox is used but is not supported on this platform");
360 sandbox_set_level(level);
364 static bool drop_privs(void) {
369 struct passwd *pw = getpwnam(switchuser);
372 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
378 // The second parameter to initgroups on macOS requires int,
379 // but __gid_t is unsigned int. There's not much we can do here.
380 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
381 setgid(pw->pw_gid) != 0) {
382 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
383 "initgroups", strerror(errno));
388 // Not supported in android NDK
395 tzset(); /* for proper timestamps in logs */
397 if(chroot(confbase) != 0 || chdir("/") != 0) {
398 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
399 "chroot", strerror(errno));
404 confbase = xstrdup("");
408 if(setuid(uid) != 0) {
409 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
410 "setuid", strerror(errno));
416 return sandbox_enter();
420 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
422 static void stop_handler(void *data, int flags) {
429 static BOOL WINAPI console_ctrl_handler(DWORD type) {
432 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
434 if(WSASetEvent(stop_io.event) == FALSE) {
441 # define NORMAL_PRIORITY_CLASS 0
442 # define BELOW_NORMAL_PRIORITY_CLASS 10
443 # define HIGH_PRIORITY_CLASS -10
444 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
447 static void cleanup(void) {
448 splay_empty_tree(&config_tree);
449 list_empty_list(&cmdline_conf);
453 int main(int argc, char **argv) {
454 program_name = argv[0];
456 if(!parse_options(argc, argv)) {
462 "%s version %s (built %s %s, protocol %d.%d)\n"
467 #ifdef HAVE_LIBGCRYPT
479 #ifndef DISABLE_LEGACY
482 #ifdef ENABLE_JUMBOGRAMS
488 #ifdef HAVE_MINIUPNPC
501 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
502 "See the AUTHORS file for a complete list.\n"
504 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
505 "and you are welcome to redistribute it under certain conditions;\n"
506 "see the file COPYING for details.\n",
507 PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
519 if(chdir(confbase) == -1) {
520 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
526 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
527 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
532 // Check if we got an umbilical fd from the process that started us
533 char *umbstr = getenv("TINC_UMBILICAL");
537 sscanf(umbstr, "%d %d", &umbilical, &colorize);
538 umbilical_colorize = colorize;
540 if(fcntl(umbilical, F_GETFL) < 0) {
547 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
555 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
559 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
564 unsetenv("LISTEN_PID");
567 gettimeofday(&now, NULL);
572 if(!read_server_config(&config_tree)) {
576 if(!read_sandbox_level()) {
580 if(debug_level == DEBUG_NOTHING) {
583 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
590 if(lzo_init() != LZO_E_OK) {
591 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
598 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
600 if(stop_io.event == FALSE) {
606 if(!do_detach || !init_service()) {
607 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
608 result = main2(argc, argv);
613 if(WSACloseEvent(stop_io.event) == FALSE) {
621 int main2(int argc, char **argv) {
625 char *priority = NULL;
633 /* Lock all pages into memory if requested.
634 * This has to be done after daemon()/fork() so it works for child.
635 * No need to do that in parent as it's very short-lived. */
636 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
637 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
644 /* Setup sockets and open device. */
646 if(!setup_network()) {
650 /* Change process priority */
652 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
653 if(!strcasecmp(priority, "Normal")) {
654 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
655 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
658 } else if(!strcasecmp(priority, "Low")) {
659 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
660 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
663 } else if(!strcasecmp(priority, "High")) {
664 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
665 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
669 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
674 /* drop privileges */
679 /* Start main loop. It only exits when tinc is killed. */
681 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
683 if(umbilical) { // snip!
684 if(write(umbilical, "", 1) != 1) {
685 // Pipe full or broken, nothing we can do about it.
692 try_outgoing_connections();
694 status = main_loop();
696 /* Shutdown properly. */
699 close_network_connections();
701 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");