2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2009 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
56 /* The name this program was run with. */
57 char *program_name = NULL;
59 /* If nonzero, display usage information and exit. */
60 bool show_help = false;
62 /* If nonzero, print the version on standard output and exit. */
63 bool show_version = false;
65 /* If nonzero, use null ciphers and skip all key exchanges. */
66 bool bypass_security = false;
68 /* If nonzero, disable swapping for this process. */
69 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;
77 /* If nonzero, write log entries to a separate file. */
78 bool use_logfile = false;
80 char *identname = NULL; /* program name for syslog */
81 char *logfilename = NULL; /* log file location */
82 char *controlcookiename = NULL;
83 char **g_argv; /* a copy of the cmdline arguments */
87 static struct option const long_options[] = {
88 {"config", required_argument, NULL, 'c'},
89 {"net", required_argument, NULL, 'n'},
90 {"help", no_argument, NULL, 1},
91 {"version", no_argument, NULL, 2},
92 {"no-detach", no_argument, NULL, 'D'},
93 {"debug", optional_argument, NULL, 'd'},
94 {"bypass-security", no_argument, NULL, 3},
95 {"mlock", no_argument, NULL, 'L'},
96 {"chroot", no_argument, NULL, 'R'},
97 {"user", required_argument, NULL, 'U'},
98 {"logfile", optional_argument, NULL, 4},
99 {"controlcookie", required_argument, NULL, 5},
104 static struct WSAData wsa_state;
105 CRITICAL_SECTION mutex;
108 static void usage(bool status) {
110 fprintf(stderr, "Try `%s --help\' for more information.\n",
113 printf("Usage: %s [option]...\n\n", program_name);
114 printf( " -c, --config=DIR Read configuration options from DIR.\n"
115 " -D, --no-detach Don't fork and detach.\n"
116 " -d, --debug[=LEVEL] Increase debug level or set it to LEVEL.\n"
117 " -n, --net=NETNAME Connect to net NETNAME.\n"
118 " -L, --mlock Lock tinc into main memory.\n"
119 " --logfile[=FILENAME] Write log entries to a logfile.\n"
120 " --controlcookie=FILENAME Write control socket cookie to FILENAME.\n"
121 " --bypass-security Disables meta protocol security, for debugging.\n"
122 " -R, --chroot chroot to NET dir at startup.\n"
123 " -U, --user=USER setuid to given USER at startup.\n" " --help Display this help and exit.\n"
124 " --version Output version information and exit.\n\n");
125 printf("Report bugs to tinc@tinc-vpn.org.\n");
129 static bool parse_options(int argc, char **argv) {
131 int option_index = 0;
133 while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
135 case 0: /* long option */
138 case 'c': /* config file */
139 confbase = xstrdup(optarg);
142 case 'D': /* no detach */
146 case 'L': /* no detach */
147 #ifndef HAVE_MLOCKALL
148 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
155 case 'd': /* inc debug level */
157 debug_level = atoi(optarg);
162 case 'n': /* net name given */
163 netname = xstrdup(optarg);
166 case 'R': /* chroot to NETNAME dir */
170 case 'U': /* setuid to USER */
174 case 1: /* show help */
178 case 2: /* show version */
182 case 3: /* bypass security */
183 bypass_security = true;
186 case 4: /* write log entries to a file */
189 logfilename = xstrdup(optarg);
192 case 5: /* open control socket here */
193 controlcookiename = xstrdup(optarg);
209 Set all files and paths according to netname
211 static void make_names(void) {
214 char installdir[1024] = "";
215 long len = sizeof installdir;
219 xasprintf(&identname, "tinc.%s", netname);
221 identname = xstrdup("tinc");
224 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
225 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
227 xasprintf(&logfilename, "%s/log/%s.log", identname);
230 xasprintf(&confbase, "%s/%s", installdir, netname);
232 xasprintf(&confbase, "%s", installdir);
234 if(!controlcookiename)
235 xasprintf(&controlcookiename, "%s/cookie", confbase);
244 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
246 if(!controlcookiename)
247 xasprintf(&controlcookiename, LOCALSTATEDIR "/run/%s.cookie", identname);
251 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
253 logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
256 xasprintf(&confbase, CONFDIR "/tinc");
260 static void free_names() {
261 if (identname) free(identname);
262 if (netname) free(netname);
263 if (controlcookiename) free(controlcookiename);
264 if (logfilename) free(logfilename);
265 if (confbase) free(confbase);
268 static bool drop_privs() {
271 logger(LOG_ERR, "%s not supported on this platform", "-U");
275 logger(LOG_ERR, "%s not supported on this platform", "-R");
281 struct passwd *pw = getpwnam(switchuser);
283 logger(LOG_ERR, "unknown user `%s'", switchuser);
287 if (initgroups(switchuser, pw->pw_gid) != 0 ||
288 setgid(pw->pw_gid) != 0) {
289 logger(LOG_ERR, "System call `%s' failed: %s",
290 "initgroups", strerror(errno));
297 tzset(); /* for proper timestamps in logs */
298 if (chroot(confbase) != 0 || chdir("/") != 0) {
299 logger(LOG_ERR, "System call `%s' failed: %s",
300 "chroot", strerror(errno));
304 confbase = xstrdup("");
307 if (setuid(uid) != 0) {
308 logger(LOG_ERR, "System call `%s' failed: %s",
309 "setuid", strerror(errno));
317 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
319 # define NORMAL_PRIORITY_CLASS 0
320 # define BELOW_NORMAL_PRIORITY_CLASS 10
321 # define HIGH_PRIORITY_CLASS -10
322 # define setpriority(level) nice(level)
325 int main(int argc, char **argv) {
326 program_name = argv[0];
328 if(!parse_options(argc, argv))
334 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
335 VERSION, __DATE__, __TIME__, PROT_CURRENT);
336 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
337 "See the AUTHORS file for a complete list.\n\n"
338 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
339 "and you are welcome to redistribute it under certain conditions;\n"
340 "see the file COPYING for details.\n");
351 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
352 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
357 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
360 logger(LOG_ERR, "Error initializing libevent!");
366 init_configuration(&config_tree);
368 /* Slllluuuuuuurrrrp! */
373 if(!read_server_config())
376 if(lzo_init() != LZO_E_OK) {
377 logger(LOG_ERR, "Error initializing LZO compressor!");
382 if(!do_detach || !init_service())
383 return main2(argc, argv);
388 int main2(int argc, char **argv) {
389 InitializeCriticalSection(&mutex);
390 EnterCriticalSection(&mutex);
397 /* Lock all pages into memory if requested.
398 * This has to be done after daemon()/fork() so it works for child.
399 * No need to do that in parent as it's very short-lived. */
400 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
401 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
407 /* Setup sockets and open device. */
415 /* Initiate all outgoing connections. */
417 try_outgoing_connections();
419 /* Change process priority */
423 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
424 if(!strcasecmp(priority, "Normal"))
425 setpriority(NORMAL_PRIORITY_CLASS);
426 else if(!strcasecmp(priority, "Low"))
427 setpriority(BELOW_NORMAL_PRIORITY_CLASS);
428 else if(!strcasecmp(priority, "High"))
429 setpriority(HIGH_PRIORITY_CLASS);
431 logger(LOG_ERR, "Invalid priority `%s`!", priority);
436 /* drop privileges */
440 /* Start main loop. It only exits when tinc is killed. */
442 status = main_loop();
444 /* Shutdown properly. */
449 close_network_connections();
452 logger(LOG_NOTICE, "Terminating");
458 exit_configuration(&config_tree);