2 tincd.c -- the main file for tincd
3 Copyright (C) 1998-2005 Ivo Timmermans
4 2000-2012 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
36 #include <openssl/rand.h>
37 #include <openssl/rsa.h>
38 #include <openssl/pem.h>
39 #include <openssl/evp.h>
40 #include <openssl/engine.h>
66 /* The name this program was run with. */
67 char *program_name = NULL;
69 /* If nonzero, display usage information and exit. */
70 static bool show_help = false;
72 /* If nonzero, print the version on standard output and exit. */
73 static bool show_version = false;
75 /* If nonzero, use null ciphers and skip all key exchanges. */
76 bool bypass_security = false;
78 /* If nonzero, disable swapping for this process. */
79 static bool do_mlock = false;
81 /* If nonzero, chroot to netdir after startup. */
82 static bool do_chroot = false;
84 /* If !NULL, do setuid to given user after startup */
85 static const char *switchuser = NULL;
87 /* If nonzero, write log entries to a separate file. */
88 bool use_logfile = false;
90 char *identname = NULL; /* program name for syslog */
91 char *logfilename = NULL; /* log file location */
92 char *pidfilename = NULL;
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 {"pidfile", required_argument, NULL, 5},
110 {"option", required_argument, NULL, 'o'},
115 static struct WSAData wsa_state;
116 CRITICAL_SECTION mutex;
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"
130 " -L, --mlock Lock tinc into main memory.\n"
131 " --logfile[=FILENAME] Write log entries to a logfile.\n"
132 " --pidfile=FILENAME Write PID and control socket cookie to FILENAME.\n"
133 " --bypass-security Disables meta protocol security, for debugging.\n"
134 " -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" " --help Display this help and exit.\n"
137 " --version Output version information and exit.\n\n");
138 printf("Report bugs to tinc@tinc-vpn.org.\n");
142 static bool parse_options(int argc, char **argv) {
145 int option_index = 0;
148 cmdline_conf = list_alloc((list_action_t)free_config);
150 while((r = getopt_long(argc, argv, "c:DLd::n:o:RU:", long_options, &option_index)) != EOF) {
152 case 0: /* long option */
155 case 'c': /* config file */
156 confbase = xstrdup(optarg);
159 case 'D': /* no detach */
163 case 'L': /* no detach */
164 #ifndef HAVE_MLOCKALL
165 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "mlockall()");
172 case 'd': /* inc debug level */
174 debug_level = atoi(optarg);
179 case 'n': /* net name given */
180 /* netname "." is special: a "top-level name" */
181 netname = strcmp(optarg, ".") != 0 ?
182 xstrdup(optarg) : NULL;
185 case 'o': /* option */
186 cfg = parse_config_line(optarg, NULL, ++lineno);
189 list_insert_tail(cmdline_conf, cfg);
192 case 'R': /* chroot to NETNAME dir */
196 case 'U': /* setuid to USER */
200 case 1: /* show help */
204 case 2: /* show version */
208 case 3: /* bypass security */
209 bypass_security = true;
212 case 4: /* write log entries to a file */
215 logfilename = xstrdup(optarg);
218 case 5: /* open control socket here */
219 pidfilename = xstrdup(optarg);
235 Set all files and paths according to netname
237 static void make_names(void) {
240 char installdir[1024] = "";
241 long len = sizeof installdir;
245 xasprintf(&identname, "tinc.%s", netname);
247 identname = xstrdup("tinc");
250 if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
251 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
253 xasprintf(&logfilename, "%s/log/%s.log", identname);
256 xasprintf(&confbase, "%s/%s", installdir, netname);
258 xasprintf(&confbase, "%s", installdir);
261 xasprintf(&pidfilename, "%s/pid", confbase);
270 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
273 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
277 xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
279 logger(DEBUG_ALWAYS, LOG_INFO, "Both netname and configuration directory given, using the latter...");
282 xasprintf(&confbase, CONFDIR "/tinc");
286 static void free_names(void) {
287 if (identname) free(identname);
288 if (netname) free(netname);
289 if (pidfilename) free(pidfilename);
290 if (logfilename) free(logfilename);
291 if (confbase) free(confbase);
294 static bool drop_privs(void) {
297 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "-U");
301 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "-R");
307 struct passwd *pw = getpwnam(switchuser);
309 logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
313 if (initgroups(switchuser, pw->pw_gid) != 0 ||
314 setgid(pw->pw_gid) != 0) {
315 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
316 "initgroups", strerror(errno));
323 tzset(); /* for proper timestamps in logs */
324 if (chroot(confbase) != 0 || chdir("/") != 0) {
325 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
326 "chroot", strerror(errno));
330 confbase = xstrdup("");
333 if (setuid(uid) != 0) {
334 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
335 "setuid", strerror(errno));
343 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
345 # define NORMAL_PRIORITY_CLASS 0
346 # define BELOW_NORMAL_PRIORITY_CLASS 10
347 # define HIGH_PRIORITY_CLASS -10
348 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
351 int main(int argc, char **argv) {
352 program_name = argv[0];
354 if(!parse_options(argc, argv))
360 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
361 VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
362 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
363 "See the AUTHORS file for a complete list.\n\n"
364 "tinc comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
365 "and you are welcome to redistribute it under certain conditions;\n"
366 "see the file COPYING for details.\n");
377 if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
378 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
383 openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
386 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing libevent!");
392 if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
395 unsetenv("LISTEN_PID");
398 init_configuration(&config_tree);
400 /* Slllluuuuuuurrrrp! */
405 if(!read_server_config())
409 if(lzo_init() != LZO_E_OK) {
410 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
416 if(!do_detach || !init_service())
417 return main2(argc, argv);
422 int main2(int argc, char **argv) {
423 InitializeCriticalSection(&mutex);
424 EnterCriticalSection(&mutex);
426 char *priority = NULL;
432 /* Lock all pages into memory if requested.
433 * This has to be done after daemon()/fork() so it works for child.
434 * No need to do that in parent as it's very short-lived. */
435 if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
436 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
442 /* Setup sockets and open device. */
450 /* Initiate all outgoing connections. */
452 try_outgoing_connections();
454 /* Change process priority */
456 if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
457 if(!strcasecmp(priority, "Normal")) {
458 if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
459 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
460 "setpriority", strerror(errno));
463 } else if(!strcasecmp(priority, "Low")) {
464 if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
465 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
466 "setpriority", strerror(errno));
469 } else if(!strcasecmp(priority, "High")) {
470 if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
471 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
472 "setpriority", strerror(errno));
476 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
481 /* drop privileges */
485 /* Start main loop. It only exits when tinc is killed. */
487 status = main_loop();
489 /* Shutdown properly. */
491 if(debug_level >= DEBUG_CONNECTIONS)
494 close_network_connections();
500 logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
506 exit_configuration(&config_tree);