2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2021 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
32 #ifdef HAVE_SYS_MMAN_H
65 /* If nonzero, display usage information and exit. */
66 static bool show_help = false;
68 /* If nonzero, print the version on standard output and exit. */
69 static bool show_version = false;
71 /* If nonzero, use null ciphers and skip all key exchanges. */
72 bool bypass_security = false;
75 /* If nonzero, disable swapping for this process. */
76 static bool do_mlock = false;
80 /* If nonzero, chroot to netdir after startup. */
81 static bool do_chroot = false;
83 /* If !NULL, do setuid to given user after startup */
84 static const char *switchuser = NULL;
87 /* If nonzero, write log entries to a separate file. */
88 bool use_logfile = false;
90 /* If nonzero, use syslog instead of stderr in no-detach mode. */
91 bool use_syslog = false;
93 char **g_argv; /* a copy of the cmdline arguments */
95 static int status = 1;
97 static struct option const long_options[] = {
98 {"config", required_argument, NULL, 'c'},
99 {"net", required_argument, NULL, 'n'},
100 {"help", no_argument, NULL, 1},
101 {"version", no_argument, NULL, 2},
102 {"no-detach", no_argument, NULL, 'D'},
103 {"debug", optional_argument, NULL, 'd'},
104 {"bypass-security", no_argument, NULL, 3},
105 {"mlock", no_argument, NULL, 'L'},
106 {"chroot", no_argument, NULL, 'R'},
107 {"user", required_argument, NULL, 'U'},
108 {"logfile", optional_argument, NULL, 4},
109 {"syslog", no_argument, NULL, 's'},
110 {"pidfile", required_argument, NULL, 5},
111 {"option", required_argument, NULL, 'o'},
116 static struct WSAData wsa_state;
117 int main2(int argc, char **argv);
120 static void usage(bool status) {
122 fprintf(stderr, "Try `%s --help\' for more information.\n",
125 printf("Usage: %s [option]...\n\n", program_name);
126 printf(" -c, --config=DIR Read configuration options from DIR.\n"
127 " -D, --no-detach Don't fork and detach.\n"
128 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
129 " -n, --net=NETNAME Connect to net NETNAME.\n"
131 " -L, --mlock Lock tinc into main memory.\n"
133 " --logfile[=FILENAME] Write log entries to a logfile.\n"
134 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
135 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
136 " --bypass-security Disables meta protocol security, for debugging.\n"
137 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
139 " -R, --chroot chroot to NET dir at startup.\n"
140 " -U, --user=USER setuid to given USER at startup.\n"
142 " --help Display this help and exit.\n"
143 " --version Output version information and exit.\n\n");
144 printf("Report bugs to tinc@tinc-vpn.org.\n");
148 static bool parse_options(int argc, char **argv) {
151 int option_index = 0;
154 cmdline_conf = list_alloc((list_action_t)free_config);
156 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
158 case 0: /* long option */
161 case 'c': /* config file */
162 confbase = xstrdup(optarg);
165 case 'D': /* no detach */
169 case 'L': /* no detach */
170 #ifndef HAVE_MLOCKALL
171 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
178 case 'd': /* increase debug level */
179 if(!optarg && optind < argc && *argv[optind] != '-') {
180 optarg = argv[optind++];
184 debug_level = atoi(optarg);
191 case 'n': /* net name given */
192 netname = xstrdup(optarg);
195 case 's': /* syslog */
200 case 'o': /* option */
201 cfg = parse_config_line(optarg, NULL, ++lineno);
207 list_insert_tail(cmdline_conf, cfg);
214 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
218 case 'R': /* chroot to NETNAME dir */
222 case 'U': /* setuid to USER */
227 case 1: /* show help */
231 case 2: /* show version */
235 case 3: /* bypass security */
236 bypass_security = true;
239 case 4: /* write log entries to a file */
243 if(!optarg && optind < argc && *argv[optind] != '-') {
244 optarg = argv[optind++];
248 logfilename = xstrdup(optarg);
253 case 5: /* open control socket here */
254 pidfilename = xstrdup(optarg);
257 case '?': /* wrong options */
267 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
272 if(!netname && (netname = getenv("NETNAME"))) {
273 netname = xstrdup(netname);
276 /* netname "." is special: a "top-level name" */
278 if(netname && (!*netname || !strcmp(netname, "."))) {
283 if(netname && !check_netname(netname, false)) {
284 fprintf(stderr, "Invalid character in netname!\n");
288 if(netname && !check_netname(netname, true)) {
289 fprintf(stderr, "Warning: unsafe character in netname!\n");
295 static bool drop_privs(void) {
300 struct passwd *pw = getpwnam(switchuser);
303 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
309 if(initgroups(switchuser, pw->pw_gid) != 0 ||
310 setgid(pw->pw_gid) != 0) {
311 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
312 "initgroups", strerror(errno));
317 // Not supported in android NDK
324 tzset(); /* for proper timestamps in logs */
326 if(chroot(confbase) != 0 || chdir("/") != 0) {
327 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
328 "chroot", strerror(errno));
333 confbase = xstrdup("");
337 if(setuid(uid) != 0) {
338 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
339 "setuid", strerror(errno));
348 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
350 static void stop_handler(void *data, int flags) {
357 static BOOL WINAPI console_ctrl_handler(DWORD type) {
360 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
362 if(WSASetEvent(stop_io.event) == FALSE) {
369 # define NORMAL_PRIORITY_CLASS 0
370 # define BELOW_NORMAL_PRIORITY_CLASS 10
371 # define HIGH_PRIORITY_CLASS -10
372 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
375 int main(int argc, char **argv) {
376 program_name = argv[0];
378 if(!parse_options(argc, argv)) {
383 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
384 BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
389 #ifdef HAVE_LIBGCRYPT
401 #ifndef DISABLE_LEGACY
404 #ifdef ENABLE_JUMBOGRAMS
410 #ifdef HAVE_MINIUPNPC
420 printf("Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
421 "See the AUTHORS file for a complete list.\n\n"
422 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
423 "and you are welcome to redistribute it under certain conditions;\n"
424 "see the file COPYING for details.\n");
439 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
440 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
445 // Check if we got an umbilical fd from the process that started us
446 char *umbstr = getenv("TINC_UMBILICAL");
449 umbilical = atoi(umbstr);
451 if(fcntl(umbilical, F_GETFL) < 0) {
458 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
466 openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
470 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
475 unsetenv("LISTEN_PID");
478 init_configuration(&config_tree);
480 /* Slllluuuuuuurrrrp! */
482 gettimeofday(&now, NULL);
483 srand(now.tv_sec + now.tv_usec);
486 if(!read_server_config()) {
491 get_config_int(lookup_config(config_tree, "LogLevel"), &debug_level);
496 if(lzo_init() != LZO_E_OK) {
497 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
504 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
506 if(stop_io.event == FALSE) {
512 if(!do_detach || !init_service()) {
513 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
514 result = main2(argc, argv);
519 if(WSACloseEvent(stop_io.event) == FALSE) {
527 int main2(int argc, char **argv) {
531 char *priority = NULL;
539 /* Lock all pages into memory if requested.
540 * This has to be done after daemon()/fork() so it works for child.
541 * No need to do that in parent as it's very short-lived. */
542 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
543 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
550 /* Setup sockets and open device. */
552 if(!setup_network()) {
556 /* Change process priority */
558 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
559 if(!strcasecmp(priority, "Normal")) {
560 if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
561 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
564 } else if(!strcasecmp(priority, "Low")) {
565 if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
566 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
569 } else if(!strcasecmp(priority, "High")) {
570 if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
571 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
575 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
580 /* drop privileges */
585 /* Start main loop. It only exits when tinc is killed. */
587 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
589 if(umbilical) { // snip!
590 write(umbilical, "", 1);
595 try_outgoing_connections();
597 status = main_loop();
599 /* Shutdown properly. */
602 close_network_connections();
604 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
610 exit_configuration(&config_tree);