2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2013 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 char **g_argv; /* a copy of the cmdline arguments */
88 static int status = 1;
90 static struct option const long_options[] = {
91 {"config", required_argument, NULL, 'c'},
92 {"net", required_argument, NULL, 'n'},
93 {"help", no_argument, NULL, 1},
94 {"version", no_argument, NULL, 2},
95 {"no-detach", no_argument, NULL, 'D'},
96 {"debug", optional_argument, NULL, 'd'},
97 {"bypass-security", no_argument, NULL, 3},
98 {"mlock", no_argument, NULL, 'L'},
99 {"chroot", no_argument, NULL, 'R'},
100 {"user", required_argument, NULL, 'U'},
101 {"logfile", optional_argument, NULL, 4},
102 {"pidfile", required_argument, NULL, 5},
103 {"option", required_argument, NULL, 'o'},
108 static struct WSAData wsa_state;
109 CRITICAL_SECTION mutex;
110 int main2(int argc, char **argv);
113 static void usage(bool status) {
115 fprintf(stderr, "Try `%s --help\' for more information.\n",
118 printf("Usage: %s [option]...\n\n", program_name);
119 printf( " -c, --config=DIR Read configuration options from DIR.\n"
120 " -D, --no-detach Don't fork and detach.\n"
121 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
122 " -n, --net=NETNAME Connect to net NETNAME.\n"
124 " -L, --mlock Lock tinc into main memory.\n"
126 " --logfile[=FILENAME] Write log entries to a logfile.\n"
127 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
128 " --bypass-security Disables meta protocol security, for debugging.\n"
129 " -o, --option[HOST.]KEY=VALUE Set global/host configuration value.\n"
131 " -R, --chroot chroot to NET dir at startup.\n"
132 " -U, --user=USER setuid to given USER at startup.\n"
134 " --help Display this help and exit.\n"
135 " --version Output version information and exit.\n\n");
136 printf("Report bugs to tinc@tinc-vpn.org.\n");
140 static bool parse_options(int argc, char **argv) {
143 int option_index = 0;
146 cmdline_conf = list_alloc((list_action_t)free_config);
148 while((r = getopt_long(argc, argv, "c:DLd::n:o:RU:", long_options, &option_index)) != EOF) {
150 case 0: /* long option */
153 case 'c': /* config file */
154 confbase = xstrdup(optarg);
157 case 'D': /* no detach */
161 case 'L': /* no detach */
162 #ifndef HAVE_MLOCKALL
163 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
170 case 'd': /* inc debug level */
172 debug_level = atoi(optarg);
177 case 'n': /* net name given */
178 netname = xstrdup(optarg);
181 case 'o': /* option */
182 cfg = parse_config_line(optarg, NULL, ++lineno);
185 list_insert_tail(cmdline_conf, cfg);
191 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
194 case 'R': /* chroot to NETNAME dir */
198 case 'U': /* setuid to USER */
203 case 1: /* show help */
207 case 2: /* show version */
211 case 3: /* bypass security */
212 bypass_security = true;
215 case 4: /* write log entries to a file */
218 logfilename = xstrdup(optarg);
221 case 5: /* open control socket here */
222 pidfilename = xstrdup(optarg);
225 case '?': /* wrong options */
234 if(!netname && (netname = getenv("NETNAME")))
235 netname = xstrdup(netname);
237 /* netname "." is special: a "top-level name" */
239 if(netname && (!*netname || !strcmp(netname, "."))) {
244 if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
245 fprintf(stderr, "Invalid character in netname!\n");
252 static bool drop_privs(void) {
256 struct passwd *pw = getpwnam(switchuser);
258 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
262 if (initgroups(switchuser, pw->pw_gid) != 0 ||
263 setgid(pw->pw_gid) != 0) {
264 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
265 "initgroups", strerror(errno));
269 // Not supported in android NDK
275 tzset(); /* for proper timestamps in logs */
276 if (chroot(confbase) != 0 || chdir("/") != 0) {
277 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
278 "chroot", strerror(errno));
282 confbase = xstrdup("");
285 if (setuid(uid) != 0) {
286 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
287 "setuid", strerror(errno));
295 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
297 # define NORMAL_PRIORITY_CLASS 0
298 # define BELOW_NORMAL_PRIORITY_CLASS 10
299 # define HIGH_PRIORITY_CLASS -10
300 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
303 int main(int argc, char **argv) {
304 program_name = argv[0];
306 if(!parse_options(argc, argv))
312 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
313 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
314 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
315 "See the AUTHORS file for a complete list.\n\n"
316 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
317 "and you are welcome to redistribute it under certain conditions;\n"
318 "see the file COPYING for details.\n");
329 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
330 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
335 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
339 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
342 unsetenv("LISTEN_PID");
345 init_configuration(&config_tree);
347 /* Slllluuuuuuurrrrp! */
349 gettimeofday(&now, NULL);
350 srand(now.tv_sec + now.tv_usec);
353 if(!read_server_config())
357 if(lzo_init() != LZO_E_OK) {
358 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
364 if(!do_detach || !init_service())
365 return main2(argc, argv);
370 int main2(int argc, char **argv) {
371 InitializeCriticalSection(&mutex);
372 EnterCriticalSection(&mutex);
374 char *priority = NULL;
380 /* Lock all pages into memory if requested.
381 * This has to be done after daemon()/fork() so it works for child.
382 * No need to do that in parent as it's very short-lived. */
383 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
384 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
390 /* Setup sockets and open device. */
398 /* Initiate all outgoing connections. */
400 try_outgoing_connections();
402 /* Change process priority */
404 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
405 if(!strcasecmp(priority, "Normal")) {
406 if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
407 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
410 } else if(!strcasecmp(priority, "Low")) {
411 if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
412 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
415 } else if(!strcasecmp(priority, "High")) {
416 if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
417 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
421 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
426 /* drop privileges */
430 /* Start main loop. It only exits when tinc is killed. */
432 status = main_loop();
434 /* Shutdown properly. */
436 if(debug_level >= DEBUG_CONNECTIONS)
439 close_network_connections();
445 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
451 exit_configuration(&config_tree);