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",
133 static const char *message =
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";
157 printf(message, program_name);
161 static bool parse_options(int argc, char **argv) {
164 int option_index = 0;
167 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
168 switch((option_t) r) {
169 case OPT_LONG_OPTION:
176 case OPT_CONFIG_FILE:
178 confbase = xstrdup(optarg);
185 case OPT_MLOCK: /* lock tincd into RAM */
186 #ifndef HAVE_MLOCKALL
187 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
194 case OPT_DEBUG: /* increase debug level */
195 if(!optarg && optind < argc && *argv[optind] != '-') {
196 optarg = argv[optind++];
200 debug_level = atoi(optarg);
209 netname = xstrdup(optarg);
218 cfg = parse_config_line(optarg, NULL, ++lineno);
224 list_insert_tail(&cmdline_conf, cfg);
229 case OPT_CHANGE_USER:
231 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
239 case OPT_CHANGE_USER:
252 case OPT_NO_SECURITY:
253 bypass_security = true;
260 if(!optarg && optind < argc && *argv[optind] != '-') {
261 optarg = argv[optind++];
266 logfilename = xstrdup(optarg);
273 pidfilename = xstrdup(optarg);
282 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
287 if(!netname && (netname = getenv("NETNAME"))) {
288 netname = xstrdup(netname);
291 /* netname "." is special: a "top-level name" */
293 if(netname && (!*netname || !strcmp(netname, "."))) {
298 if(netname && !check_netname(netname, false)) {
299 fprintf(stderr, "Invalid character in netname!\n");
303 if(netname && !check_netname(netname, true)) {
304 fprintf(stderr, "Warning: unsafe character in netname!\n");
311 list_empty_list(&cmdline_conf);
315 static bool drop_privs(void) {
320 struct passwd *pw = getpwnam(switchuser);
323 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
329 // The second parameter to initgroups on macOS requires int,
330 // but __gid_t is unsigned int. There's not much we can do here.
331 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
332 setgid(pw->pw_gid) != 0) {
333 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
334 "initgroups", strerror(errno));
339 // Not supported in android NDK
346 tzset(); /* for proper timestamps in logs */
348 if(chroot(confbase) != 0 || chdir("/") != 0) {
349 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
350 "chroot", strerror(errno));
355 confbase = xstrdup("");
359 if(setuid(uid) != 0) {
360 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
361 "setuid", strerror(errno));
370 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
372 static void stop_handler(void *data, int flags) {
379 static BOOL WINAPI console_ctrl_handler(DWORD type) {
382 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
384 if(WSASetEvent(stop_io.event) == FALSE) {
391 # define NORMAL_PRIORITY_CLASS 0
392 # define BELOW_NORMAL_PRIORITY_CLASS 10
393 # define HIGH_PRIORITY_CLASS -10
394 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
397 static void cleanup(void) {
398 splay_empty_tree(&config_tree);
399 list_empty_list(&cmdline_conf);
403 int main(int argc, char **argv) {
404 program_name = argv[0];
406 if(!parse_options(argc, argv)) {
411 static const char *message =
412 "%s version %s (built %s %s, protocol %d.%d)\n"
417 #ifdef HAVE_LIBGCRYPT
429 #ifndef DISABLE_LEGACY
432 #ifdef ENABLE_JUMBOGRAMS
438 #ifdef HAVE_MINIUPNPC
448 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
449 "See the AUTHORS file for a complete list.\n"
451 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
452 "and you are welcome to redistribute it under certain conditions;\n"
453 "see the file COPYING for details.\n";
455 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
467 if(chdir(confbase) == -1) {
468 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
474 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
475 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
480 // Check if we got an umbilical fd from the process that started us
481 char *umbstr = getenv("TINC_UMBILICAL");
485 sscanf(umbstr, "%d %d", &umbilical, &colorize);
486 umbilical_colorize = colorize;
488 if(fcntl(umbilical, F_GETFL) < 0) {
495 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
503 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
507 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
512 unsetenv("LISTEN_PID");
515 gettimeofday(&now, NULL);
520 if(!read_server_config(&config_tree)) {
524 if(debug_level == DEBUG_NOTHING) {
527 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
534 if(lzo_init() != LZO_E_OK) {
535 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
542 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
544 if(stop_io.event == FALSE) {
550 if(!do_detach || !init_service()) {
551 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
552 result = main2(argc, argv);
557 if(WSACloseEvent(stop_io.event) == FALSE) {
565 int main2(int argc, char **argv) {
569 char *priority = NULL;
577 /* Lock all pages into memory if requested.
578 * This has to be done after daemon()/fork() so it works for child.
579 * No need to do that in parent as it's very short-lived. */
580 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
581 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
588 /* Setup sockets and open device. */
590 if(!setup_network()) {
594 /* Change process priority */
596 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
597 if(!strcasecmp(priority, "Normal")) {
598 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
599 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
602 } else if(!strcasecmp(priority, "Low")) {
603 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
604 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
607 } else if(!strcasecmp(priority, "High")) {
608 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
609 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
613 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
618 /* drop privileges */
623 /* Start main loop. It only exits when tinc is killed. */
625 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
627 if(umbilical) { // snip!
628 if(write(umbilical, "", 1) != 1) {
629 // Pipe full or broken, nothing we can do about it.
636 try_outgoing_connections();
638 status = main_loop();
640 /* Shutdown properly. */
643 close_network_connections();
645 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");