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
61 /* If nonzero, display usage information and exit. */
62 static bool show_help = false;
64 /* If nonzero, print the version on standard output and exit. */
65 static bool show_version = 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 char **g_argv; /* a copy of the cmdline arguments */
82 static int status = 1;
84 typedef enum option_t {
89 OPT_CONFIG_FILE = 'c',
95 OPT_CHANGE_USER = 'U',
107 static struct option const long_options[] = {
108 {"config", required_argument, NULL, OPT_CONFIG_FILE},
109 {"net", required_argument, NULL, OPT_NETNAME},
110 {"no-detach", no_argument, NULL, OPT_NO_DETACH},
111 {"debug", optional_argument, NULL, OPT_DEBUG},
112 {"mlock", no_argument, NULL, OPT_MLOCK},
113 {"chroot", no_argument, NULL, OPT_CHROOT},
114 {"user", required_argument, NULL, OPT_CHANGE_USER},
115 {"syslog", no_argument, NULL, OPT_SYSLOG},
116 {"option", required_argument, NULL, OPT_OPTION},
117 {"help", no_argument, NULL, OPT_HELP},
118 {"version", no_argument, NULL, OPT_VERSION},
119 {"bypass-security", no_argument, NULL, OPT_NO_SECURITY},
120 {"logfile", optional_argument, NULL, OPT_LOGFILE},
121 {"pidfile", required_argument, NULL, OPT_PIDFILE},
126 static struct WSAData wsa_state;
127 int main2(int argc, char **argv);
130 static void usage(bool status) {
132 fprintf(stderr, "Try `%s --help\' for more information.\n",
136 "Usage: %s [option]...\n"
138 " -c, --config=DIR Read configuration options from DIR.\n"
139 " -D, --no-detach Don't fork and detach.\n"
140 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
141 " -n, --net=NETNAME Connect to net NETNAME.\n"
143 " -L, --mlock Lock tinc into main memory.\n"
145 " --logfile[=FILENAME] Write log entries to a logfile.\n"
146 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
147 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
148 " --bypass-security Disables meta protocol security, for debugging.\n"
149 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
151 " -R, --chroot chroot to NET dir at startup.\n"
152 " -U, --user=USER setuid to given USER at startup.\n"
154 " --help Display this help and exit.\n"
155 " --version Output version information and exit.\n"
157 "Report bugs to tinc@tinc-vpn.org.\n",
162 // Try to resolve path to absolute, return a copy of the argument if this fails.
163 static char *get_path_arg(char *arg) {
164 char *result = absolute_path(arg);
167 result = xstrdup(arg);
173 static bool parse_options(int argc, char **argv) {
176 int option_index = 0;
179 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
180 switch((option_t) r) {
181 case OPT_LONG_OPTION:
188 case OPT_CONFIG_FILE:
191 confbase = get_path_arg(optarg);
198 case OPT_MLOCK: /* lock tincd into RAM */
199 #ifndef HAVE_MLOCKALL
200 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
207 case OPT_DEBUG: /* increase debug level */
208 if(!optarg && optind < argc && *argv[optind] != '-') {
209 optarg = argv[optind++];
213 debug_level = atoi(optarg);
223 netname = xstrdup(optarg);
232 cfg = parse_config_line(optarg, NULL, ++lineno);
238 list_insert_tail(&cmdline_conf, cfg);
243 case OPT_CHANGE_USER:
245 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
253 case OPT_CHANGE_USER:
266 case OPT_NO_SECURITY:
267 bypass_security = true;
274 if(!optarg && optind < argc && *argv[optind] != '-') {
275 optarg = argv[optind++];
280 logfilename = get_path_arg(optarg);
288 pidfilename = get_path_arg(optarg);
297 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
302 if(!netname && (netname = getenv("NETNAME"))) {
303 netname = xstrdup(netname);
306 /* netname "." is special: a "top-level name" */
308 if(netname && (!*netname || !strcmp(netname, "."))) {
313 if(netname && !check_netname(netname, false)) {
314 fprintf(stderr, "Invalid character in netname!\n");
318 if(netname && !check_netname(netname, true)) {
319 fprintf(stderr, "Warning: unsafe character in netname!\n");
326 list_empty_list(&cmdline_conf);
330 static bool read_sandbox_level(void) {
331 sandbox_level_t level;
334 if(get_config_string(lookup_config(&config_tree, "Sandbox"), &value)) {
335 if(!strcasecmp("off", value)) {
336 level = SANDBOX_NONE;
337 } else if(!strcasecmp("normal", value)) {
338 level = SANDBOX_NORMAL;
339 } else if(!strcasecmp("high", value)) {
340 level = SANDBOX_HIGH;
342 logger(DEBUG_ALWAYS, LOG_ERR, "Bad sandbox value %s!", value);
350 level = SANDBOX_NORMAL;
352 level = SANDBOX_NONE;
358 if(level > SANDBOX_NONE) {
359 logger(DEBUG_ALWAYS, LOG_ERR, "Sandbox is used but is not supported on this platform");
364 sandbox_set_level(level);
368 static bool drop_privs(void) {
373 struct passwd *pw = getpwnam(switchuser);
376 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
382 // The second parameter to initgroups on macOS requires int,
383 // but __gid_t is unsigned int. There's not much we can do here.
384 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
385 setgid(pw->pw_gid) != 0) {
386 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
387 "initgroups", strerror(errno));
392 // Not supported in android NDK
399 tzset(); /* for proper timestamps in logs */
401 if(chroot(confbase) != 0 || chdir("/") != 0) {
402 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
403 "chroot", strerror(errno));
408 confbase = xstrdup("");
412 if(setuid(uid) != 0) {
413 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
414 "setuid", strerror(errno));
420 return sandbox_enter();
424 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
426 static void stop_handler(void *data, int flags) {
433 static BOOL WINAPI console_ctrl_handler(DWORD type) {
436 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
438 if(WSASetEvent(stop_io.event) == FALSE) {
445 # define NORMAL_PRIORITY_CLASS 0
446 # define BELOW_NORMAL_PRIORITY_CLASS 10
447 # define HIGH_PRIORITY_CLASS -10
448 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
451 static void cleanup(void) {
452 splay_empty_tree(&config_tree);
453 list_empty_list(&cmdline_conf);
457 int main(int argc, char **argv) {
458 program_name = argv[0];
460 if(!parse_options(argc, argv)) {
466 "%s version %s (built %s %s, protocol %d.%d)\n"
471 #ifdef HAVE_LIBGCRYPT
483 #ifndef DISABLE_LEGACY
486 #ifdef ENABLE_JUMBOGRAMS
492 #ifdef HAVE_MINIUPNPC
505 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
506 "See the AUTHORS file for a complete list.\n"
508 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
509 "and you are welcome to redistribute it under certain conditions;\n"
510 "see the file COPYING for details.\n",
511 PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
523 if(chdir(confbase) == -1) {
524 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
530 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
531 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
536 // Check if we got an umbilical fd from the process that started us
537 char *umbstr = getenv("TINC_UMBILICAL");
541 sscanf(umbstr, "%d %d", &umbilical, &colorize);
542 umbilical_colorize = colorize;
544 if(fcntl(umbilical, F_GETFL) < 0) {
551 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
559 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
563 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
568 unsetenv("LISTEN_PID");
571 gettimeofday(&now, NULL);
576 if(!read_server_config(&config_tree)) {
580 if(!read_sandbox_level()) {
584 if(debug_level == DEBUG_NOTHING) {
587 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
594 if(lzo_init() != LZO_E_OK) {
595 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
602 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
604 if(stop_io.event == FALSE) {
610 if(!do_detach || !init_service()) {
611 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
612 result = main2(argc, argv);
617 if(WSACloseEvent(stop_io.event) == FALSE) {
625 int main2(int argc, char **argv) {
629 char *priority = NULL;
637 /* Lock all pages into memory if requested.
638 * This has to be done after daemon()/fork() so it works for child.
639 * No need to do that in parent as it's very short-lived. */
640 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
641 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
648 /* Setup sockets and open device. */
650 if(!setup_network()) {
654 /* Change process priority */
656 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
657 if(!strcasecmp(priority, "Normal")) {
658 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
659 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
662 } else if(!strcasecmp(priority, "Low")) {
663 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
664 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
667 } else if(!strcasecmp(priority, "High")) {
668 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
669 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
673 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
678 /* drop privileges */
683 /* Start main loop. It only exits when tinc is killed. */
685 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
687 if(umbilical) { // snip!
688 if(write(umbilical, "", 1) != 1) {
689 // Pipe full or broken, nothing we can do about it.
696 try_outgoing_connections();
702 status = main_loop();
708 /* Shutdown properly. */
711 close_network_connections();
713 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");