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
58 /* If nonzero, display usage information and exit. */
59 static bool show_help = false;
61 /* If nonzero, print the version on standard output and exit. */
62 static bool show_version = false;
65 /* If nonzero, disable swapping for this process. */
66 static bool do_mlock = false;
70 /* If nonzero, chroot to netdir after startup. */
71 static bool do_chroot = false;
73 /* If !NULL, do setuid to given user after startup */
74 static const char *switchuser = NULL;
77 char **g_argv; /* a copy of the cmdline arguments */
79 static int status = 1;
81 static struct option const long_options[] = {
82 {"config", required_argument, NULL, 'c'},
83 {"net", required_argument, NULL, 'n'},
84 {"help", no_argument, NULL, 1},
85 {"version", no_argument, NULL, 2},
86 {"no-detach", no_argument, NULL, 'D'},
87 {"debug", optional_argument, NULL, 'd'},
88 {"bypass-security", no_argument, NULL, 3},
89 {"mlock", no_argument, NULL, 'L'},
90 {"chroot", no_argument, NULL, 'R'},
91 {"user", required_argument, NULL, 'U'},
92 {"logfile", optional_argument, NULL, 4},
93 {"syslog", no_argument, NULL, 's'},
94 {"pidfile", required_argument, NULL, 5},
95 {"option", required_argument, NULL, 'o'},
100 static struct WSAData wsa_state;
101 int main2(int argc, char **argv);
104 static void usage(bool status) {
106 fprintf(stderr, "Try `%s --help\' for more information.\n",
109 static const char *message =
110 "Usage: %s [option]...\n"
112 " -c, --config=DIR Read configuration options from DIR.\n"
113 " -D, --no-detach Don't fork and detach.\n"
114 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
115 " -n, --net=NETNAME Connect to net NETNAME.\n"
117 " -L, --mlock Lock tinc into main memory.\n"
119 " --logfile[=FILENAME] Write log entries to a logfile.\n"
120 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
121 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
122 " --bypass-security Disables meta protocol security, for debugging.\n"
123 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
125 " -R, --chroot chroot to NET dir at startup.\n"
126 " -U, --user=USER setuid to given USER at startup.\n"
128 " --help Display this help and exit.\n"
129 " --version Output version information and exit.\n"
131 "Report bugs to tinc@tinc-vpn.org.\n";
133 printf(message, program_name);
137 static bool parse_options(int argc, char **argv) {
140 int option_index = 0;
143 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
145 case 0: /* long option */
148 case 'c': /* config file */
150 confbase = xstrdup(optarg);
153 case 'D': /* no detach */
157 case 'L': /* no detach */
158 #ifndef HAVE_MLOCKALL
159 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
166 case 'd': /* increase debug level */
167 if(!optarg && optind < argc && *argv[optind] != '-') {
168 optarg = argv[optind++];
172 debug_level = atoi(optarg);
179 case 'n': /* net name given */
181 netname = xstrdup(optarg);
184 case 's': /* syslog */
189 case 'o': /* option */
190 cfg = parse_config_line(optarg, NULL, ++lineno);
196 list_insert_tail(&cmdline_conf, cfg);
203 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
207 case 'R': /* chroot to NETNAME dir */
211 case 'U': /* setuid to USER */
216 case 1: /* show help */
220 case 2: /* show version */
224 case 3: /* bypass security */
225 bypass_security = true;
228 case 4: /* write log entries to a file */
232 if(!optarg && optind < argc && *argv[optind] != '-') {
233 optarg = argv[optind++];
238 logfilename = xstrdup(optarg);
243 case 5: /* open control socket here */
245 pidfilename = xstrdup(optarg);
248 case '?': /* wrong options */
258 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
263 if(!netname && (netname = getenv("NETNAME"))) {
264 netname = xstrdup(netname);
267 /* netname "." is special: a "top-level name" */
269 if(netname && (!*netname || !strcmp(netname, "."))) {
274 if(netname && !check_netname(netname, false)) {
275 fprintf(stderr, "Invalid character in netname!\n");
279 if(netname && !check_netname(netname, true)) {
280 fprintf(stderr, "Warning: unsafe character in netname!\n");
287 list_empty_list(&cmdline_conf);
291 static bool drop_privs(void) {
296 struct passwd *pw = getpwnam(switchuser);
299 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
305 // The second parameter to initgroups on macOS requires int,
306 // but __gid_t is unsigned int. There's not much we can do here.
307 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
308 setgid(pw->pw_gid) != 0) {
309 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
310 "initgroups", strerror(errno));
315 // Not supported in android NDK
322 tzset(); /* for proper timestamps in logs */
324 if(chroot(confbase) != 0 || chdir("/") != 0) {
325 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
326 "chroot", strerror(errno));
331 confbase = xstrdup("");
335 if(setuid(uid) != 0) {
336 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
337 "setuid", strerror(errno));
346 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
348 static void stop_handler(void *data, int flags) {
355 static BOOL WINAPI console_ctrl_handler(DWORD type) {
358 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
360 if(WSASetEvent(stop_io.event) == FALSE) {
367 # define NORMAL_PRIORITY_CLASS 0
368 # define BELOW_NORMAL_PRIORITY_CLASS 10
369 # define HIGH_PRIORITY_CLASS -10
370 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
373 static void cleanup(void) {
374 splay_empty_tree(&config_tree);
375 list_empty_list(&cmdline_conf);
379 int main(int argc, char **argv) {
380 program_name = argv[0];
382 if(!parse_options(argc, argv)) {
387 static const char *message =
388 "%s version %s (built %s %s, protocol %d.%d)\n"
393 #ifdef HAVE_LIBGCRYPT
405 #ifndef DISABLE_LEGACY
408 #ifdef ENABLE_JUMBOGRAMS
414 #ifdef HAVE_MINIUPNPC
424 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
425 "See the AUTHORS file for a complete list.\n"
427 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
428 "and you are welcome to redistribute it under certain conditions;\n"
429 "see the file COPYING for details.\n";
431 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
443 if(chdir(confbase) == -1) {
444 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
450 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
451 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
456 // Check if we got an umbilical fd from the process that started us
457 char *umbstr = getenv("TINC_UMBILICAL");
460 umbilical = atoi(umbstr);
462 if(fcntl(umbilical, F_GETFL) < 0) {
469 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
477 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
481 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
486 unsetenv("LISTEN_PID");
489 gettimeofday(&now, NULL);
493 if(!read_server_config(&config_tree)) {
497 if(debug_level == DEBUG_NOTHING) {
500 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
507 if(lzo_init() != LZO_E_OK) {
508 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
515 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
517 if(stop_io.event == FALSE) {
523 if(!do_detach || !init_service()) {
524 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
525 result = main2(argc, argv);
530 if(WSACloseEvent(stop_io.event) == FALSE) {
538 int main2(int argc, char **argv) {
542 char *priority = NULL;
550 /* Lock all pages into memory if requested.
551 * This has to be done after daemon()/fork() so it works for child.
552 * No need to do that in parent as it's very short-lived. */
553 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
554 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
561 /* Setup sockets and open device. */
563 if(!setup_network()) {
567 /* Change process priority */
569 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
570 if(!strcasecmp(priority, "Normal")) {
571 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
572 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
575 } else if(!strcasecmp(priority, "Low")) {
576 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
577 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
580 } else if(!strcasecmp(priority, "High")) {
581 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
582 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
586 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
591 /* drop privileges */
596 /* Start main loop. It only exits when tinc is killed. */
598 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
600 if(umbilical) { // snip!
601 if(write(umbilical, "", 1) != 1) {
602 // Pipe full or broken, nothing we can do about it.
609 try_outgoing_connections();
611 status = main_loop();
613 /* Shutdown properly. */
616 close_network_connections();
618 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");