2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2016 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
61 /* If nonzero, display usage information and exit. */
62 static bool show_help = false;
64 /* If nonzero, print the version on standard output and exit. */
65 static bool show_version = false;
67 /* If nonzero, use null ciphers and skip all key exchanges. */
68 bool bypass_security = false;
71 /* If nonzero, disable swapping for this process. */
72 static bool do_mlock = false;
76 /* If nonzero, chroot to netdir after startup. */
77 static bool do_chroot = false;
79 /* If !NULL, do setuid to given user after startup */
80 static const char *switchuser = NULL;
83 /* If nonzero, write log entries to a separate file. */
84 bool use_logfile = false;
86 /* If nonzero, use syslog instead of stderr in no-detach mode. */
87 bool use_syslog = false;
89 char **g_argv; /* a copy of the cmdline arguments */
91 static int status = 1;
93 static struct option const long_options[] = {
94 {"config", required_argument, NULL, 'c'},
95 {"net", required_argument, NULL, 'n'},
96 {"help", no_argument, NULL, 1},
97 {"version", no_argument, NULL, 2},
98 {"no-detach", no_argument, NULL, 'D'},
99 {"debug", optional_argument, NULL, 'd'},
100 {"bypass-security", no_argument, NULL, 3},
101 {"mlock", no_argument, NULL, 'L'},
102 {"chroot", no_argument, NULL, 'R'},
103 {"user", required_argument, NULL, 'U'},
104 {"logfile", optional_argument, NULL, 4},
105 {"syslog", no_argument, NULL, 's'},
106 {"pidfile", required_argument, NULL, 5},
107 {"option", required_argument, NULL, 'o'},
112 static struct WSAData wsa_state;
113 int main2(int argc, char **argv);
116 static void usage(bool status) {
118 fprintf(stderr, "Try `%s --help\' for more information.\n",
121 printf("Usage: %s [option]...\n\n", program_name);
122 printf( " -c, --config=DIR Read configuration options from DIR.\n"
123 " -D, --no-detach Don't fork and detach.\n"
124 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
125 " -n, --net=NETNAME Connect to net NETNAME.\n"
127 " -L, --mlock Lock tinc into main memory.\n"
129 " --logfile[=FILENAME] Write log entries to a logfile.\n"
130 " -s --syslog Use syslog instead of stderr with --no-detach.\n"
131 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
132 " --bypass-security Disables meta protocol security, for debugging.\n"
133 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
135 " -R, --chroot chroot to NET dir at startup.\n"
136 " -U, --user=USER setuid to given USER at startup.\n"
138 " --help Display this help and exit.\n"
139 " --version Output version information and exit.\n\n");
140 printf("Report bugs to tinc@tinc-vpn.org.\n");
144 static bool parse_options(int argc, char **argv) {
147 int option_index = 0;
150 cmdline_conf = list_alloc((list_action_t)free_config);
152 while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
154 case 0: /* long option */
157 case 'c': /* config file */
158 confbase = xstrdup(optarg);
161 case 'D': /* no detach */
165 case 'L': /* no detach */
166 #ifndef HAVE_MLOCKALL
167 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
174 case 'd': /* increase debug level */
175 if(!optarg && optind < argc && *argv[optind] != '-')
176 optarg = argv[optind++];
178 debug_level = atoi(optarg);
183 case 'n': /* net name given */
184 netname = xstrdup(optarg);
187 case 's': /* syslog */
192 case 'o': /* option */
193 cfg = parse_config_line(optarg, NULL, ++lineno);
196 list_insert_tail(cmdline_conf, cfg);
202 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
205 case 'R': /* chroot to NETNAME dir */
209 case 'U': /* setuid to USER */
214 case 1: /* show help */
218 case 2: /* show version */
222 case 3: /* bypass security */
223 bypass_security = true;
226 case 4: /* write log entries to a file */
229 if(!optarg && optind < argc && *argv[optind] != '-')
230 optarg = argv[optind++];
232 logfilename = xstrdup(optarg);
235 case 5: /* open control socket here */
236 pidfilename = xstrdup(optarg);
239 case '?': /* wrong options */
249 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
254 if(!netname && (netname = getenv("NETNAME")))
255 netname = xstrdup(netname);
257 /* netname "." is special: a "top-level name" */
259 if(netname && (!*netname || !strcmp(netname, "."))) {
264 if(netname && !check_netname(netname, false)) {
265 fprintf(stderr, "Invalid character in netname!\n");
269 if(netname && !check_netname(netname, true))
270 fprintf(stderr, "Warning: unsafe character in netname!\n");
275 static bool drop_privs(void) {
279 struct passwd *pw = getpwnam(switchuser);
281 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
285 if (initgroups(switchuser, pw->pw_gid) != 0 ||
286 setgid(pw->pw_gid) != 0) {
287 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
288 "initgroups", strerror(errno));
292 // Not supported in android NDK
298 tzset(); /* for proper timestamps in logs */
299 if (chroot(confbase) != 0 || chdir("/") != 0) {
300 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
301 "chroot", strerror(errno));
305 confbase = xstrdup("");
308 if (setuid(uid) != 0) {
309 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
310 "setuid", strerror(errno));
318 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
320 static void stop_handler(void *data, int flags) {
324 static BOOL WINAPI console_ctrl_handler(DWORD type) {
325 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
326 if (WSASetEvent(stop_io.event) == FALSE)
331 # define NORMAL_PRIORITY_CLASS 0
332 # define BELOW_NORMAL_PRIORITY_CLASS 10
333 # define HIGH_PRIORITY_CLASS -10
334 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
337 int main(int argc, char **argv) {
338 program_name = argv[0];
340 if(!parse_options(argc, argv))
347 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
348 BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
349 printf("Copyright (C) 1998-2016 Ivo Timmermans, Guus Sliepen and others.\n"
350 "See the AUTHORS file for a complete list.\n\n"
351 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
352 "and you are welcome to redistribute it under certain conditions;\n"
353 "see the file COPYING for details.\n");
364 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
365 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
369 // Check if we got an umbilical fd from the process that started us
370 char *umbstr = getenv("TINC_UMBILICAL");
372 umbilical = atoi(umbstr);
373 if(fcntl(umbilical, F_GETFL) < 0)
377 fcntl(umbilical, F_SETFD, FD_CLOEXEC);
382 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
386 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
389 unsetenv("LISTEN_PID");
392 init_configuration(&config_tree);
394 /* Slllluuuuuuurrrrp! */
396 gettimeofday(&now, NULL);
397 srand(now.tv_sec + now.tv_usec);
400 if(!read_server_config())
404 if(lzo_init() != LZO_E_OK) {
405 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
411 io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
412 if (stop_io.event == FALSE)
416 if(!do_detach || !init_service()) {
417 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
418 result = main2(argc, argv);
422 if (WSACloseEvent(stop_io.event) == FALSE)
428 int main2(int argc, char **argv) {
430 char *priority = NULL;
436 /* Lock all pages into memory if requested.
437 * This has to be done after daemon()/fork() so it works for child.
438 * No need to do that in parent as it's very short-lived. */
439 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
440 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
446 /* Setup sockets and open device. */
451 /* Change process priority */
453 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
454 if(!strcasecmp(priority, "Normal")) {
455 if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
456 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
459 } else if(!strcasecmp(priority, "Low")) {
460 if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
461 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
464 } else if(!strcasecmp(priority, "High")) {
465 if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
466 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
470 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
475 /* drop privileges */
479 /* Start main loop. It only exits when tinc is killed. */
481 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
483 if(umbilical) { // snip!
484 write(umbilical, "", 1);
489 try_outgoing_connections();
491 status = main_loop();
493 /* Shutdown properly. */
496 close_network_connections();
498 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
504 exit_configuration(&config_tree);