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
59 /* If nonzero, display usage information and exit. */
60 static bool show_help = false;
62 /* If nonzero, print the version on standard output and exit. */
63 static bool show_version = false;
66 /* If nonzero, disable swapping for this process. */
67 static bool do_mlock = false;
71 /* If nonzero, chroot to netdir after startup. */
72 static bool do_chroot = false;
74 /* If !NULL, do setuid to given user after startup */
75 static const char *switchuser = NULL;
78 char **g_argv; /* a copy of the cmdline arguments */
80 static int status = 1;
82 typedef enum option_t {
87 OPT_CONFIG_FILE = 'c',
93 OPT_CHANGE_USER = 'U',
105 static struct option const long_options[] = {
106 {"config", required_argument, NULL, OPT_CONFIG_FILE},
107 {"net", required_argument, NULL, OPT_NETNAME},
108 {"no-detach", no_argument, NULL, OPT_NO_DETACH},
109 {"debug", optional_argument, NULL, OPT_DEBUG},
110 {"mlock", no_argument, NULL, OPT_MLOCK},
111 {"chroot", no_argument, NULL, OPT_CHROOT},
112 {"user", required_argument, NULL, OPT_CHANGE_USER},
113 {"syslog", no_argument, NULL, OPT_SYSLOG},
114 {"option", required_argument, NULL, OPT_OPTION},
115 {"help", no_argument, NULL, OPT_HELP},
116 {"version", no_argument, NULL, OPT_VERSION},
117 {"bypass-security", no_argument, NULL, OPT_NO_SECURITY},
118 {"logfile", optional_argument, NULL, OPT_LOGFILE},
119 {"pidfile", required_argument, NULL, OPT_PIDFILE},
124 static struct WSAData wsa_state;
125 int main2(int argc, char **argv);
128 static void usage(bool status) {
130 fprintf(stderr, "Try `%s --help\' for more information.\n",
134 "Usage: %s [option]...\n"
136 " -c, --config=DIR Read configuration options from DIR.\n"
137 " -D, --no-detach Don't fork and detach.\n"
138 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
139 " -n, --net=NETNAME Connect to net NETNAME.\n"
141 " -L, --mlock Lock tinc into main memory.\n"
143 " --logfile[=FILENAME] Write log entries to a logfile.\n"
144 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
145 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
146 " --bypass-security Disables meta protocol security, for debugging.\n"
147 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
149 " -R, --chroot chroot to NET dir at startup.\n"
150 " -U, --user=USER setuid to given USER at startup.\n"
152 " --help Display this help and exit.\n"
153 " --version Output version information and exit.\n"
155 "Report bugs to tinc@tinc-vpn.org.\n",
160 // Try to resolve path to absolute, return a copy of the argument if this fails.
161 static char *get_path_arg(char *arg) {
162 char *result = absolute_path(arg);
165 result = xstrdup(arg);
171 static bool parse_options(int argc, char **argv) {
174 int option_index = 0;
177 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
178 switch((option_t) r) {
179 case OPT_LONG_OPTION:
186 case OPT_CONFIG_FILE:
188 confbase = get_path_arg(optarg);
195 case OPT_MLOCK: /* lock tincd into RAM */
196 #ifndef HAVE_MLOCKALL
197 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
204 case OPT_DEBUG: /* increase debug level */
205 if(!optarg && optind < argc && *argv[optind] != '-') {
206 optarg = argv[optind++];
210 debug_level = atoi(optarg);
219 netname = xstrdup(optarg);
228 cfg = parse_config_line(optarg, NULL, ++lineno);
234 list_insert_tail(&cmdline_conf, cfg);
239 case OPT_CHANGE_USER:
241 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
249 case OPT_CHANGE_USER:
262 case OPT_NO_SECURITY:
263 bypass_security = true;
270 if(!optarg && optind < argc && *argv[optind] != '-') {
271 optarg = argv[optind++];
276 logfilename = get_path_arg(optarg);
283 pidfilename = get_path_arg(optarg);
292 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
297 if(!netname && (netname = getenv("NETNAME"))) {
298 netname = xstrdup(netname);
301 /* netname "." is special: a "top-level name" */
303 if(netname && (!*netname || !strcmp(netname, "."))) {
308 if(netname && !check_netname(netname, false)) {
309 fprintf(stderr, "Invalid character in netname!\n");
313 if(netname && !check_netname(netname, true)) {
314 fprintf(stderr, "Warning: unsafe character in netname!\n");
321 list_empty_list(&cmdline_conf);
325 static bool drop_privs(void) {
330 struct passwd *pw = getpwnam(switchuser);
333 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
339 // The second parameter to initgroups on macOS requires int,
340 // but __gid_t is unsigned int. There's not much we can do here.
341 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
342 setgid(pw->pw_gid) != 0) {
343 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
344 "initgroups", strerror(errno));
349 // Not supported in android NDK
356 tzset(); /* for proper timestamps in logs */
358 if(chroot(confbase) != 0 || chdir("/") != 0) {
359 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
360 "chroot", strerror(errno));
365 confbase = xstrdup("");
369 if(setuid(uid) != 0) {
370 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
371 "setuid", strerror(errno));
380 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
382 static void stop_handler(void *data, int flags) {
389 static BOOL WINAPI console_ctrl_handler(DWORD type) {
392 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
394 if(WSASetEvent(stop_io.event) == FALSE) {
401 # define NORMAL_PRIORITY_CLASS 0
402 # define BELOW_NORMAL_PRIORITY_CLASS 10
403 # define HIGH_PRIORITY_CLASS -10
404 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
407 static void cleanup(void) {
408 splay_empty_tree(&config_tree);
409 list_empty_list(&cmdline_conf);
413 int main(int argc, char **argv) {
414 program_name = argv[0];
416 if(!parse_options(argc, argv)) {
422 "%s version %s (built %s %s, protocol %d.%d)\n"
427 #ifdef HAVE_LIBGCRYPT
439 #ifndef DISABLE_LEGACY
442 #ifdef ENABLE_JUMBOGRAMS
448 #ifdef HAVE_MINIUPNPC
458 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
459 "See the AUTHORS file for a complete list.\n"
461 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
462 "and you are welcome to redistribute it under certain conditions;\n"
463 "see the file COPYING for details.\n",
464 PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
476 if(chdir(confbase) == -1) {
477 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
483 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
484 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
489 // Check if we got an umbilical fd from the process that started us
490 char *umbstr = getenv("TINC_UMBILICAL");
494 sscanf(umbstr, "%d %d", &umbilical, &colorize);
495 umbilical_colorize = colorize;
497 if(fcntl(umbilical, F_GETFL) < 0) {
504 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
512 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
516 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
521 unsetenv("LISTEN_PID");
524 gettimeofday(&now, NULL);
529 if(!read_server_config(&config_tree)) {
533 if(debug_level == DEBUG_NOTHING) {
536 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
543 if(lzo_init() != LZO_E_OK) {
544 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
551 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
553 if(stop_io.event == FALSE) {
559 if(!do_detach || !init_service()) {
560 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
561 result = main2(argc, argv);
566 if(WSACloseEvent(stop_io.event) == FALSE) {
574 int main2(int argc, char **argv) {
578 char *priority = NULL;
586 /* Lock all pages into memory if requested.
587 * This has to be done after daemon()/fork() so it works for child.
588 * No need to do that in parent as it's very short-lived. */
589 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
590 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
597 /* Setup sockets and open device. */
599 if(!setup_network()) {
603 /* Change process priority */
605 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
606 if(!strcasecmp(priority, "Normal")) {
607 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
608 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
611 } else if(!strcasecmp(priority, "Low")) {
612 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
613 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
616 } else if(!strcasecmp(priority, "High")) {
617 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
618 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
622 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
627 /* drop privileges */
632 /* Start main loop. It only exits when tinc is killed. */
634 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
636 if(umbilical) { // snip!
637 if(write(umbilical, "", 1) != 1) {
638 // Pipe full or broken, nothing we can do about it.
645 try_outgoing_connections();
647 status = main_loop();
649 /* Shutdown properly. */
652 close_network_connections();
654 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");