README.git: tinc 1.1 needs libevent
[tinc] / src / tincd.c
1 /*
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>
7
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.
12
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.
17
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.
21 */
22
23 #include "system.h"
24
25 /* Darwin (MacOS/X) needs the following definition... */
26 #ifndef _P1003_1B_VISIBLE
27 #define _P1003_1B_VISIBLE
28 #endif
29
30 #ifdef HAVE_SYS_MMAN_H
31 #include <sys/mman.h>
32 #endif
33
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>
39
40 #ifdef HAVE_LZO
41 #include LZO1X_H
42 #endif
43
44 #ifndef HAVE_MINGW
45 #include <pwd.h>
46 #include <grp.h>
47 #include <time.h>
48 #endif
49
50 #include <getopt.h>
51
52 #include "conf.h"
53 #include "control.h"
54 #include "crypto.h"
55 #include "device.h"
56 #include "logger.h"
57 #include "net.h"
58 #include "netutl.h"
59 #include "process.h"
60 #include "protocol.h"
61 #include "utils.h"
62 #include "xalloc.h"
63
64 /* The name this program was run with. */
65 char *program_name = NULL;
66
67 /* If nonzero, display usage information and exit. */
68 bool show_help = false;
69
70 /* If nonzero, print the version on standard output and exit.  */
71 bool show_version = false;
72
73 /* If nonzero, use null ciphers and skip all key exchanges. */
74 bool bypass_security = false;
75
76 /* If nonzero, disable swapping for this process. */
77 bool do_mlock = false;
78
79 /* If nonzero, chroot to netdir after startup. */
80 static bool do_chroot = false;
81
82 /* If !NULL, do setuid to given user after startup */
83 static const char *switchuser = NULL;
84
85 /* If nonzero, write log entries to a separate file. */
86 bool use_logfile = false;
87
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 */
92
93 static int status;
94
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},
108         {NULL, 0, NULL, 0}
109 };
110
111 #ifdef HAVE_MINGW
112 static struct WSAData wsa_state;
113 CRITICAL_SECTION mutex;
114 #endif
115
116 static void usage(bool status) {
117         if(status)
118                 fprintf(stderr, "Try `%s --help\' for more information.\n",
119                                 program_name);
120         else {
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");
134         }
135 }
136
137 static bool parse_options(int argc, char **argv) {
138         int r;
139         int option_index = 0;
140
141         while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
142                 switch (r) {
143                         case 0:                         /* long option */
144                                 break;
145
146                         case 'c':                               /* config file */
147                                 confbase = xstrdup(optarg);
148                                 break;
149
150                         case 'D':                               /* no detach */
151                                 do_detach = false;
152                                 break;
153
154                         case 'L':                               /* no detach */
155 #ifndef HAVE_MLOCKALL
156                                 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
157                                 return false;
158 #else
159                                 do_mlock = true;
160                                 break;
161 #endif
162
163                         case 'd':                               /* inc debug level */
164                                 if(optarg)
165                                         debug_level = atoi(optarg);
166                                 else
167                                         debug_level++;
168                                 break;
169
170                         case 'n':                               /* net name given */
171                                 netname = xstrdup(optarg);
172                                 break;
173
174                         case 'R':                               /* chroot to NETNAME dir */
175                                 do_chroot = true;
176                                 break;
177
178                         case 'U':                               /* setuid to USER */
179                                 switchuser = optarg;
180                                 break;
181
182                         case 1:                                 /* show help */
183                                 show_help = true;
184                                 break;
185
186                         case 2:                                 /* show version */
187                                 show_version = true;
188                                 break;
189
190                         case 3:                                 /* bypass security */
191                                 bypass_security = true;
192                                 break;
193
194                         case 4:                                 /* write log entries to a file */
195                                 use_logfile = true;
196                                 if(optarg)
197                                         logfilename = xstrdup(optarg);
198                                 break;
199
200                         case 5:                                 /* open control socket here */
201                                 controlcookiename = xstrdup(optarg);
202                                 break;
203
204                         case '?':
205                                 usage(true);
206                                 return false;
207
208                         default:
209                                 break;
210                 }
211         }
212
213         return true;
214 }
215
216 /*
217   Set all files and paths according to netname
218 */
219 static void make_names(void) {
220 #ifdef HAVE_MINGW
221         HKEY key;
222         char installdir[1024] = "";
223         long len = sizeof installdir;
224 #endif
225
226         if(netname)
227                 xasprintf(&identname, "tinc.%s", netname);
228         else
229                 identname = xstrdup("tinc");
230
231 #ifdef HAVE_MINGW
232         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
233                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
234                         if(!logfilename)
235                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
236                         if(!confbase) {
237                                 if(netname)
238                                         xasprintf(&confbase, "%s/%s", installdir, netname);
239                                 else
240                                         xasprintf(&confbase, "%s", installdir);
241                         }
242                         if(!controlcookiename)
243                                 xasprintf(&controlcookiename, "%s/cookie", confbase);
244                 }
245                 RegCloseKey(key);
246                 if(*installdir)
247                         return;
248         }
249 #endif
250
251         if(!logfilename)
252                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
253
254         if(!controlcookiename)
255                 xasprintf(&controlcookiename, LOCALSTATEDIR "/run/%s.cookie", identname);
256
257         if(netname) {
258                 if(!confbase)
259                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
260                 else
261                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
262         } else {
263                 if(!confbase)
264                         xasprintf(&confbase, CONFDIR "/tinc");
265         }
266 }
267
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);
274 }
275
276 static bool drop_privs() {
277 #ifdef HAVE_MINGW
278         if (switchuser) {
279                 logger(LOG_ERR, "%s not supported on this platform", "-U");
280                 return false;
281         }
282         if (do_chroot) {
283                 logger(LOG_ERR, "%s not supported on this platform", "-R");
284                 return false;
285         }
286 #else
287         uid_t uid = 0;
288         if (switchuser) {
289                 struct passwd *pw = getpwnam(switchuser);
290                 if (!pw) {
291                         logger(LOG_ERR, "unknown user `%s'", switchuser);
292                         return false;
293                 }
294                 uid = pw->pw_uid;
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));
299                         return false;
300                 }
301                 endgrent();
302                 endpwent();
303         }
304         if (do_chroot) {
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));
309                         return false;
310                 }
311                 free(confbase);
312                 confbase = xstrdup("");
313         }
314         if (switchuser)
315                 if (setuid(uid) != 0) {
316                         logger(LOG_ERR, "System call `%s' failed: %s",
317                                "setuid", strerror(errno));
318                         return false;
319                 }
320 #endif
321         return true;
322 }
323
324 #ifdef HAVE_MINGW
325 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
326 #else
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)
331 #endif
332
333 int main(int argc, char **argv) {
334         program_name = argv[0];
335
336         if(!parse_options(argc, argv))
337                 return 1;
338         
339         make_names();
340
341         if(show_version) {
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");
349
350                 return 0;
351         }
352
353         if(show_help) {
354                 usage(false);
355                 return 0;
356         }
357
358 #ifdef HAVE_MINGW
359         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
360                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
361                 return 1;
362         }
363 #endif
364
365         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
366
367         if(!event_init()) {
368                 logger(LOG_ERR, "Error initializing libevent!");
369                 return 1;
370         }
371
372         g_argv = argv;
373
374         init_configuration(&config_tree);
375
376         /* Slllluuuuuuurrrrp! */
377
378         srand(time(NULL));
379         crypto_init();
380
381         if(!read_server_config())
382                 return 1;
383
384 #ifdef HAVE_LZO
385         if(lzo_init() != LZO_E_OK) {
386                 logger(LOG_ERR, "Error initializing LZO compressor!");
387                 return 1;
388         }
389 #endif
390
391 #ifdef HAVE_MINGW
392         if(!do_detach || !init_service())
393                 return main2(argc, argv);
394         else
395                 return 1;
396 }
397
398 int main2(int argc, char **argv) {
399         InitializeCriticalSection(&mutex);
400         EnterCriticalSection(&mutex);
401 #endif
402
403         if(!detach())
404                 return 1;
405
406 #ifdef HAVE_MLOCKALL
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",
412                    strerror(errno));
413                 return 1;
414         }
415 #endif
416
417         /* Setup sockets and open device. */
418
419         if(!setup_network())
420                 goto end;
421
422         if(!init_control())
423                 return 1;
424
425         /* Initiate all outgoing connections. */
426
427         try_outgoing_connections();
428
429         /* Change process priority */
430
431         char *priority = 0;
432
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);
440                 else {
441                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
442                         goto end;
443                 }
444         }
445
446         /* drop privileges */
447         if (!drop_privs())
448                 goto end;
449
450         /* Start main loop. It only exits when tinc is killed. */
451
452         status = main_loop();
453
454         /* Shutdown properly. */
455
456         ifdebug(CONNECTIONS)
457                 dump_device_stats();
458
459         close_network_connections();
460
461 end:
462         logger(LOG_NOTICE, "Terminating");
463
464         exit_control();
465
466         crypto_exit();
467
468         exit_configuration(&config_tree);
469         free_names();
470
471         return status;
472 }