Merge branch 'master' into 1.1
[tinc] / src / tincd.c
1 /*
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>
9
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.
14
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.
19
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.
23 */
24
25 #include "system.h"
26
27 /* Darwin (MacOS/X) needs the following definition... */
28 #ifndef _P1003_1B_VISIBLE
29 #define _P1003_1B_VISIBLE
30 #endif
31
32 #ifdef HAVE_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35
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>
41
42 #ifdef HAVE_LZO
43 #include LZO1X_H
44 #endif
45
46 #ifndef HAVE_MINGW
47 #include <pwd.h>
48 #include <grp.h>
49 #include <time.h>
50 #endif
51
52 #include <getopt.h>
53
54 #include "conf.h"
55 #include "control.h"
56 #include "crypto.h"
57 #include "device.h"
58 #include "logger.h"
59 #include "net.h"
60 #include "netutl.h"
61 #include "process.h"
62 #include "protocol.h"
63 #include "utils.h"
64 #include "xalloc.h"
65
66 /* The name this program was run with. */
67 char *program_name = NULL;
68
69 /* If nonzero, display usage information and exit. */
70 static bool show_help = false;
71
72 /* If nonzero, print the version on standard output and exit.  */
73 static bool show_version = false;
74
75 /* If nonzero, use null ciphers and skip all key exchanges. */
76 bool bypass_security = false;
77
78 /* If nonzero, disable swapping for this process. */
79 static bool do_mlock = false;
80
81 /* If nonzero, chroot to netdir after startup. */
82 static bool do_chroot = false;
83
84 /* If !NULL, do setuid to given user after startup */
85 static const char *switchuser = NULL;
86
87 /* If nonzero, write log entries to a separate file. */
88 bool use_logfile = false;
89
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 */
94
95 static int status = 1;
96
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'},
111         {NULL, 0, NULL, 0}
112 };
113
114 #ifdef HAVE_MINGW
115 static struct WSAData wsa_state;
116 CRITICAL_SECTION mutex;
117 int main2(int argc, char **argv);
118 #endif
119
120 static void usage(bool status) {
121         if(status)
122                 fprintf(stderr, "Try `%s --help\' for more information.\n",
123                                 program_name);
124         else {
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");
139         }
140 }
141
142 static bool parse_options(int argc, char **argv) {
143         config_t *cfg;
144         int r;
145         int option_index = 0;
146         int lineno = 0;
147
148         cmdline_conf = list_alloc((list_action_t)free_config);
149
150         while((r = getopt_long(argc, argv, "c:DLd::n:o:RU:", long_options, &option_index)) != EOF) {
151                 switch (r) {
152                         case 0:                         /* long option */
153                                 break;
154
155                         case 'c':                               /* config file */
156                                 confbase = xstrdup(optarg);
157                                 break;
158
159                         case 'D':                               /* no detach */
160                                 do_detach = false;
161                                 break;
162
163                         case 'L':                               /* no detach */
164 #ifndef HAVE_MLOCKALL
165                                 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "mlockall()");
166                                 return false;
167 #else
168                                 do_mlock = true;
169                                 break;
170 #endif
171
172                         case 'd':                               /* inc debug level */
173                                 if(optarg)
174                                         debug_level = atoi(optarg);
175                                 else
176                                         debug_level++;
177                                 break;
178
179                         case 'n':                               /* net name given */
180                                 netname = xstrdup(optarg);
181                                 break;
182
183                         case 'o':                               /* option */
184                                 cfg = parse_config_line(optarg, NULL, ++lineno);
185                                 if (!cfg)
186                                         return false;
187                                 list_insert_tail(cmdline_conf, cfg);
188                                 break;
189
190                         case 'R':                               /* chroot to NETNAME dir */
191                                 do_chroot = true;
192                                 break;
193
194                         case 'U':                               /* setuid to USER */
195                                 switchuser = optarg;
196                                 break;
197
198                         case 1:                                 /* show help */
199                                 show_help = true;
200                                 break;
201
202                         case 2:                                 /* show version */
203                                 show_version = true;
204                                 break;
205
206                         case 3:                                 /* bypass security */
207                                 bypass_security = true;
208                                 break;
209
210                         case 4:                                 /* write log entries to a file */
211                                 use_logfile = true;
212                                 if(optarg)
213                                         logfilename = xstrdup(optarg);
214                                 break;
215
216                         case 5:                                 /* open control socket here */
217                                 pidfilename = xstrdup(optarg);
218                                 break;
219
220                         case '?':
221                                 usage(true);
222                                 return false;
223
224                         default:
225                                 break;
226                 }
227         }
228
229         if(!netname && (netname = getenv("NETNAME")))
230                 netname = xstrdup(netname);
231
232         /* netname "." is special: a "top-level name" */
233
234         if(netname && !strcmp(netname, ".")) {
235                 free(netname);
236                 netname = NULL;
237         }
238
239         return true;
240 }
241
242 /*
243   Set all files and paths according to netname
244 */
245 static void make_names(void) {
246 #ifdef HAVE_MINGW
247         HKEY key;
248         char installdir[1024] = "";
249         long len = sizeof installdir;
250 #endif
251
252         if(netname)
253                 xasprintf(&identname, "tinc.%s", netname);
254         else
255                 identname = xstrdup("tinc");
256
257 #ifdef HAVE_MINGW
258         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
259                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
260                         if(!logfilename)
261                                 xasprintf(&logfilename, "%s" SLASH "log" SLASH "%s.log", identname);
262                         if(!confbase) {
263                                 if(netname)
264                                         xasprintf(&confbase, "%s" SLASH "%s", installdir, netname);
265                                 else
266                                         xasprintf(&confbase, "%s", installdir);
267                         }
268                         if(!pidfilename)
269                                 xasprintf(&pidfilename, "%s" SLASH "pid", confbase);
270                 }
271                 RegCloseKey(key);
272                 if(*installdir)
273                         return;
274         }
275 #endif
276
277         if(!logfilename)
278                 xasprintf(&logfilename, LOCALSTATEDIR SLASH "log" SLASH "%s.log", identname);
279
280         if(!pidfilename)
281                 xasprintf(&pidfilename, LOCALSTATEDIR SLASH "run" SLASH "%s.pid", identname);
282
283         if(netname) {
284                 if(!confbase)
285                         xasprintf(&confbase, CONFDIR SLASH "tinc" SLASH "%s", netname);
286                 else
287                         logger(DEBUG_ALWAYS, LOG_INFO, "Both netname and configuration directory given, using the latter...");
288         } else {
289                 if(!confbase)
290                         xasprintf(&confbase, CONFDIR SLASH "tinc");
291         }
292 }
293
294 static void free_names(void) {
295         if (identname) free(identname);
296         if (netname) free(netname);
297         if (pidfilename) free(pidfilename);
298         if (logfilename) free(logfilename);
299         if (confbase) free(confbase);
300 }
301
302 static bool drop_privs(void) {
303 #ifdef HAVE_MINGW
304         if (switchuser) {
305                 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "-U");
306                 return false;
307         }
308         if (do_chroot) {
309                 logger(DEBUG_ALWAYS, LOG_ERR, "%s not supported on this platform", "-R");
310                 return false;
311         }
312 #else
313         uid_t uid = 0;
314         if (switchuser) {
315                 struct passwd *pw = getpwnam(switchuser);
316                 if (!pw) {
317                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
318                         return false;
319                 }
320                 uid = pw->pw_uid;
321                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
322                     setgid(pw->pw_gid) != 0) {
323                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
324                                "initgroups", strerror(errno));
325                         return false;
326                 }
327                 endgrent();
328                 endpwent();
329         }
330         if (do_chroot) {
331                 tzset();        /* for proper timestamps in logs */
332                 if (chroot(confbase) != 0 || chdir("/") != 0) {
333                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
334                                "chroot", strerror(errno));
335                         return false;
336                 }
337                 free(confbase);
338                 confbase = xstrdup("");
339         }
340         if (switchuser)
341                 if (setuid(uid) != 0) {
342                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
343                                "setuid", strerror(errno));
344                         return false;
345                 }
346 #endif
347         return true;
348 }
349
350 #ifdef HAVE_MINGW
351 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
352 #else
353 # define NORMAL_PRIORITY_CLASS 0
354 # define BELOW_NORMAL_PRIORITY_CLASS 10
355 # define HIGH_PRIORITY_CLASS -10
356 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
357 #endif
358
359 int main(int argc, char **argv) {
360         program_name = argv[0];
361
362         if(!parse_options(argc, argv))
363                 return 1;
364         
365         make_names();
366
367         if(show_version) {
368                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
369                            VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
370                 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
371                                 "See the AUTHORS file for a complete list.\n\n"
372                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
373                                 "and you are welcome to redistribute it under certain conditions;\n"
374                                 "see the file COPYING for details.\n");
375
376                 return 0;
377         }
378
379         if(show_help) {
380                 usage(false);
381                 return 0;
382         }
383
384 #ifdef HAVE_MINGW
385         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
386                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
387                 return 1;
388         }
389 #endif
390
391         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
392
393         g_argv = argv;
394
395         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
396                 do_detach = false;
397 #ifdef HAVE_UNSETENV
398         unsetenv("LISTEN_PID");
399 #endif
400
401         init_configuration(&config_tree);
402
403         /* Slllluuuuuuurrrrp! */
404
405         srand(time(NULL));
406         crypto_init();
407
408         if(!read_server_config())
409                 return 1;
410
411 #ifdef HAVE_LZO
412         if(lzo_init() != LZO_E_OK) {
413                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
414                 return 1;
415         }
416 #endif
417
418 #ifdef HAVE_MINGW
419         if(!do_detach || !init_service())
420                 return main2(argc, argv);
421         else
422                 return 1;
423 }
424
425 int main2(int argc, char **argv) {
426         InitializeCriticalSection(&mutex);
427         EnterCriticalSection(&mutex);
428 #endif
429         char *priority = NULL;
430
431         if(!detach())
432                 return 1;
433
434 #ifdef HAVE_MLOCKALL
435         /* Lock all pages into memory if requested.
436          * This has to be done after daemon()/fork() so it works for child.
437          * No need to do that in parent as it's very short-lived. */
438         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
439                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
440                    strerror(errno));
441                 return 1;
442         }
443 #endif
444
445         if(!event_init()) {
446                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing libevent!");
447                 return 1;
448         }
449
450         /* Setup sockets and open device. */
451
452         if(!setup_network())
453                 goto end_nonet;
454
455         if(!init_control())
456                 goto end_nonet;
457
458         /* Initiate all outgoing connections. */
459
460         try_outgoing_connections();
461
462         /* Change process priority */
463
464         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
465                 if(!strcasecmp(priority, "Normal")) {
466                         if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
467                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
468                                        "setpriority", strerror(errno));
469                                 goto end;
470                         }
471                 } else if(!strcasecmp(priority, "Low")) {
472                         if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
473                                        logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
474                                        "setpriority", strerror(errno));
475                                 goto end;
476                         }
477                 } else if(!strcasecmp(priority, "High")) {
478                         if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
479                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
480                                        "setpriority", strerror(errno));
481                                 goto end;
482                         }
483                 } else {
484                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
485                         goto end;
486                 }
487         }
488
489         /* drop privileges */
490         if (!drop_privs())
491                 goto end;
492
493         /* Start main loop. It only exits when tinc is killed. */
494
495         status = main_loop();
496
497         /* Shutdown properly. */
498
499         if(debug_level >= DEBUG_CONNECTIONS)
500                 devops.dump_stats();
501
502         close_network_connections();
503
504 end:
505         exit_control();
506
507 end_nonet:
508         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
509
510         free(priority);
511
512         crypto_exit();
513
514         exit_configuration(&config_tree);
515         free(cmdline_conf);
516         free_names();
517
518         return status;
519 }