2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5 2008 Max Rijevski <maksuf@gmail.com>
6 2009 Michael Tokarev <mjt@tls.msk.ru>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 /* Darwin (MacOS/X) needs the following definition... */
26 #ifndef _P1003_1B_VISIBLE
27 #define _P1003_1B_VISIBLE
30 #ifdef HAVE_SYS_MMAN_H
34 #include <openssl/rand.h>
35 #include <openssl/rsa.h>
36 #include <openssl/pem.h>
37 #include <openssl/evp.h>
38 #include <openssl/engine.h>
64 /* The name this program was run with. */
65 char *program_name = NULL;
67 /* If nonzero, display usage information and exit. */
68 bool show_help = false;
70 /* If nonzero, print the version on standard output and exit. */
71 bool show_version = false;
73 /* If nonzero, use null ciphers and skip all key exchanges. */
74 bool bypass_security = false;
76 /* If nonzero, disable swapping for this process. */
77 bool do_mlock = false;
79 /* If nonzero, chroot to netdir after startup. */
80 static bool do_chroot = false;
82 /* If !NULL, do setuid to given user after startup */
83 static const char *switchuser = NULL;
85 /* If nonzero, write log entries to a separate file. */
86 bool use_logfile = false;
88 char *identname = NULL; /* program name for syslog */
89 char *logfilename = NULL; /* log file location */
90 char *controlcookiename = NULL;
91 char **g_argv; /* a copy of the cmdline arguments */
95 static struct option const long_options[] = {
96 {"config", required_argument, NULL, 'c'},
97 {"net", required_argument, NULL, 'n'},
98 {"help", no_argument, NULL, 1},
99 {"version", no_argument, NULL, 2},
100 {"no-detach", no_argument, NULL, 'D'},
101 {"debug", optional_argument, NULL, 'd'},
102 {"bypass-security", no_argument, NULL, 3},
103 {"mlock", no_argument, NULL, 'L'},
104 {"chroot", no_argument, NULL, 'R'},
105 {"user", required_argument, NULL, 'U'},
106 {"logfile", optional_argument, NULL, 4},
107 {"controlcookie", required_argument, NULL, 5},
112 static struct WSAData wsa_state;
113 CRITICAL_SECTION mutex;
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"
126 " -L, --mlock Lock tinc into main memory.\n"
127 " --logfile[=FILENAME] Write log entries to a logfile.\n"
128 " --controlcookie=FILENAME Write control socket cookie to FILENAME.\n"
129 " --bypass-security Disables meta protocol security, for debugging.\n"
130 " -R, --chroot chroot to NET dir at startup.\n"
131 " -U, --user=USER setuid to given USER at startup.\n" " --help Display this help and exit.\n"
132 " --version Output version information and exit.\n\n");
133 printf("Report bugs to tinc@tinc-vpn.org.\n");
137 static bool parse_options(int argc, char **argv) {
139 int option_index = 0;
141 while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
143 case 0: /* long option */
146 case 'c': /* config file */
147 confbase = xstrdup(optarg);
150 case 'D': /* no detach */
154 case 'L': /* no detach */
155 #ifndef HAVE_MLOCKALL
156 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
163 case 'd': /* inc debug level */
165 debug_level = atoi(optarg);
170 case 'n': /* net name given */
171 netname = xstrdup(optarg);
174 case 'R': /* chroot to NETNAME dir */
178 case 'U': /* setuid to USER */
182 case 1: /* show help */
186 case 2: /* show version */
190 case 3: /* bypass security */
191 bypass_security = true;
194 case 4: /* write log entries to a file */
197 logfilename = xstrdup(optarg);
200 case 5: /* open control socket here */
201 controlcookiename = xstrdup(optarg);
217 Set all files and paths according to netname
219 static void make_names(void) {
222 char installdir[1024] = "";
223 long len = sizeof installdir;
227 xasprintf(&identname, "tinc.%s", netname);
229 identname = xstrdup("tinc");
232 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
233 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
235 xasprintf(&logfilename, "%s/log/%s.log", identname);
238 xasprintf(&confbase, "%s/%s", installdir, netname);
240 xasprintf(&confbase, "%s", installdir);
242 if(!controlcookiename)
243 xasprintf(&controlcookiename, "%s/cookie", confbase);
252 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
254 if(!controlcookiename)
255 xasprintf(&controlcookiename, LOCALSTATEDIR "/run/%s.cookie", identname);
259 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
261 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
264 xasprintf(&confbase, CONFDIR "/tinc");
268 static void free_names() {
269 if (identname) free(identname);
270 if (netname) free(netname);
271 if (controlcookiename) free(controlcookiename);
272 if (logfilename) free(logfilename);
273 if (confbase) free(confbase);
276 static bool drop_privs() {
279 logger(LOG_ERR, "%s not supported on this platform", "-U");
283 logger(LOG_ERR, "%s not supported on this platform", "-R");
289 struct passwd *pw = getpwnam(switchuser);
291 logger(LOG_ERR, "unknown user `%s'", switchuser);
295 if (initgroups(switchuser, pw->pw_gid) != 0 ||
296 setgid(pw->pw_gid) != 0) {
297 logger(LOG_ERR, "System call `%s' failed: %s",
298 "initgroups", strerror(errno));
305 tzset(); /* for proper timestamps in logs */
306 if (chroot(confbase) != 0 || chdir("/") != 0) {
307 logger(LOG_ERR, "System call `%s' failed: %s",
308 "chroot", strerror(errno));
312 confbase = xstrdup("");
315 if (setuid(uid) != 0) {
316 logger(LOG_ERR, "System call `%s' failed: %s",
317 "setuid", strerror(errno));
325 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
327 # define NORMAL_PRIORITY_CLASS 0
328 # define BELOW_NORMAL_PRIORITY_CLASS 10
329 # define HIGH_PRIORITY_CLASS -10
330 # define setpriority(level) nice(level)
333 int main(int argc, char **argv) {
334 program_name = argv[0];
336 if(!parse_options(argc, argv))
342 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
343 VERSION, __DATE__, __TIME__, PROT_CURRENT);
344 printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
345 "See the AUTHORS file for a complete list.\n\n"
346 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
347 "and you are welcome to redistribute it under certain conditions;\n"
348 "see the file COPYING for details.\n");
359 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
360 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
365 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
368 logger(LOG_ERR, "Error initializing libevent!");
374 init_configuration(&config_tree);
376 /* Slllluuuuuuurrrrp! */
381 if(!read_server_config())
385 if(lzo_init() != LZO_E_OK) {
386 logger(LOG_ERR, "Error initializing LZO compressor!");
392 if(!do_detach || !init_service())
393 return main2(argc, argv);
398 int main2(int argc, char **argv) {
399 InitializeCriticalSection(&mutex);
400 EnterCriticalSection(&mutex);
407 /* Lock all pages into memory if requested.
408 * This has to be done after daemon()/fork() so it works for child.
409 * No need to do that in parent as it's very short-lived. */
410 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
411 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
417 /* Setup sockets and open device. */
425 /* Initiate all outgoing connections. */
427 try_outgoing_connections();
429 /* Change process priority */
433 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
434 if(!strcasecmp(priority, "Normal"))
435 setpriority(NORMAL_PRIORITY_CLASS);
436 else if(!strcasecmp(priority, "Low"))
437 setpriority(BELOW_NORMAL_PRIORITY_CLASS);
438 else if(!strcasecmp(priority, "High"))
439 setpriority(HIGH_PRIORITY_CLASS);
441 logger(LOG_ERR, "Invalid priority `%s`!", priority);
446 /* drop privileges */
450 /* Start main loop. It only exits when tinc is killed. */
452 status = main_loop();
454 /* Shutdown properly. */
459 close_network_connections();
462 logger(LOG_NOTICE, "Terminating");
468 exit_configuration(&config_tree);