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 static struct option const long_options[] = {
83 {"config", required_argument, NULL, 'c'},
84 {"net", required_argument, NULL, 'n'},
85 {"help", no_argument, NULL, 1},
86 {"version", no_argument, NULL, 2},
87 {"no-detach", no_argument, NULL, 'D'},
88 {"debug", optional_argument, NULL, 'd'},
89 {"bypass-security", no_argument, NULL, 3},
90 {"mlock", no_argument, NULL, 'L'},
91 {"chroot", no_argument, NULL, 'R'},
92 {"user", required_argument, NULL, 'U'},
93 {"logfile", optional_argument, NULL, 4},
94 {"syslog", no_argument, NULL, 's'},
95 {"pidfile", required_argument, NULL, 5},
96 {"option", required_argument, NULL, 'o'},
101 static struct WSAData wsa_state;
102 int main2(int argc, char **argv);
105 static void usage(bool status) {
107 fprintf(stderr, "Try `%s --help\' for more information.\n",
110 static const char *message =
111 "Usage: %s [option]...\n"
113 " -c, --config=DIR Read configuration options from DIR.\n"
114 " -D, --no-detach Don't fork and detach.\n"
115 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
116 " -n, --net=NETNAME Connect to net NETNAME.\n"
118 " -L, --mlock Lock tinc into main memory.\n"
120 " --logfile[=FILENAME] Write log entries to a logfile.\n"
121 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
122 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
123 " --bypass-security Disables meta protocol security, for debugging.\n"
124 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
126 " -R, --chroot chroot to NET dir at startup.\n"
127 " -U, --user=USER setuid to given USER at startup.\n"
129 " --help Display this help and exit.\n"
130 " --version Output version information and exit.\n"
132 "Report bugs to tinc@tinc-vpn.org.\n";
134 printf(message, program_name);
138 static bool parse_options(int argc, char **argv) {
141 int option_index = 0;
144 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
146 case 0: /* long option */
149 case 'c': /* config file */
151 confbase = xstrdup(optarg);
154 case 'D': /* no detach */
158 case 'L': /* no detach */
159 #ifndef HAVE_MLOCKALL
160 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
167 case 'd': /* increase debug level */
168 if(!optarg && optind < argc && *argv[optind] != '-') {
169 optarg = argv[optind++];
173 debug_level = atoi(optarg);
180 case 'n': /* net name given */
182 netname = xstrdup(optarg);
185 case 's': /* syslog */
190 case 'o': /* option */
191 cfg = parse_config_line(optarg, NULL, ++lineno);
197 list_insert_tail(&cmdline_conf, cfg);
204 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
208 case 'R': /* chroot to NETNAME dir */
212 case 'U': /* setuid to USER */
217 case 1: /* show help */
221 case 2: /* show version */
225 case 3: /* bypass security */
226 bypass_security = true;
229 case 4: /* write log entries to a file */
233 if(!optarg && optind < argc && *argv[optind] != '-') {
234 optarg = argv[optind++];
239 logfilename = xstrdup(optarg);
244 case 5: /* open control socket here */
246 pidfilename = xstrdup(optarg);
249 case '?': /* wrong options */
259 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
264 if(!netname && (netname = getenv("NETNAME"))) {
265 netname = xstrdup(netname);
268 /* netname "." is special: a "top-level name" */
270 if(netname && (!*netname || !strcmp(netname, "."))) {
275 if(netname && !check_netname(netname, false)) {
276 fprintf(stderr, "Invalid character in netname!\n");
280 if(netname && !check_netname(netname, true)) {
281 fprintf(stderr, "Warning: unsafe character in netname!\n");
288 list_empty_list(&cmdline_conf);
292 static bool drop_privs(void) {
297 struct passwd *pw = getpwnam(switchuser);
300 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
306 // The second parameter to initgroups on macOS requires int,
307 // but __gid_t is unsigned int. There's not much we can do here.
308 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
309 setgid(pw->pw_gid) != 0) {
310 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
311 "initgroups", strerror(errno));
316 // Not supported in android NDK
323 tzset(); /* for proper timestamps in logs */
325 if(chroot(confbase) != 0 || chdir("/") != 0) {
326 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
327 "chroot", strerror(errno));
332 confbase = xstrdup("");
336 if(setuid(uid) != 0) {
337 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
338 "setuid", strerror(errno));
347 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
349 static void stop_handler(void *data, int flags) {
356 static BOOL WINAPI console_ctrl_handler(DWORD type) {
359 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
361 if(WSASetEvent(stop_io.event) == FALSE) {
368 # define NORMAL_PRIORITY_CLASS 0
369 # define BELOW_NORMAL_PRIORITY_CLASS 10
370 # define HIGH_PRIORITY_CLASS -10
371 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
374 static void cleanup(void) {
375 splay_empty_tree(&config_tree);
376 list_empty_list(&cmdline_conf);
380 int main(int argc, char **argv) {
381 program_name = argv[0];
383 if(!parse_options(argc, argv)) {
388 static const char *message =
389 "%s version %s (built %s %s, protocol %d.%d)\n"
394 #ifdef HAVE_LIBGCRYPT
406 #ifndef DISABLE_LEGACY
409 #ifdef ENABLE_JUMBOGRAMS
415 #ifdef HAVE_MINIUPNPC
425 "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
426 "See the AUTHORS file for a complete list.\n"
428 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
429 "and you are welcome to redistribute it under certain conditions;\n"
430 "see the file COPYING for details.\n";
432 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
444 if(chdir(confbase) == -1) {
445 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
451 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
452 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
457 // Check if we got an umbilical fd from the process that started us
458 char *umbstr = getenv("TINC_UMBILICAL");
461 umbilical = atoi(umbstr);
463 if(fcntl(umbilical, F_GETFL) < 0) {
470 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
478 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
482 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
487 unsetenv("LISTEN_PID");
490 gettimeofday(&now, NULL);
495 if(!read_server_config(&config_tree)) {
499 if(debug_level == DEBUG_NOTHING) {
502 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
509 if(lzo_init() != LZO_E_OK) {
510 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
517 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
519 if(stop_io.event == FALSE) {
525 if(!do_detach || !init_service()) {
526 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
527 result = main2(argc, argv);
532 if(WSACloseEvent(stop_io.event) == FALSE) {
540 int main2(int argc, char **argv) {
544 char *priority = NULL;
552 /* Lock all pages into memory if requested.
553 * This has to be done after daemon()/fork() so it works for child.
554 * No need to do that in parent as it's very short-lived. */
555 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
556 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
563 /* Setup sockets and open device. */
565 if(!setup_network()) {
569 /* Change process priority */
571 if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
572 if(!strcasecmp(priority, "Normal")) {
573 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
574 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
577 } else if(!strcasecmp(priority, "Low")) {
578 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
579 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
582 } else if(!strcasecmp(priority, "High")) {
583 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
584 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
588 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
593 /* drop privileges */
598 /* Start main loop. It only exits when tinc is killed. */
600 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
602 if(umbilical) { // snip!
603 if(write(umbilical, "", 1) != 1) {
604 // Pipe full or broken, nothing we can do about it.
611 try_outgoing_connections();
613 status = main_loop();
615 /* Shutdown properly. */
618 close_network_connections();
620 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");