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-2009 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 LZO1X_H
35
36 #ifndef HAVE_MINGW
37 #include <pwd.h>
38 #include <grp.h>
39 #include <time.h>
40 #endif
41
42 #include <getopt.h>
43
44 #include "conf.h"
45 #include "control.h"
46 #include "crypto.h"
47 #include "device.h"
48 #include "logger.h"
49 #include "net.h"
50 #include "netutl.h"
51 #include "process.h"
52 #include "protocol.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 /* The name this program was run with. */
57 char *program_name = NULL;
58
59 /* If nonzero, display usage information and exit. */
60 bool show_help = false;
61
62 /* If nonzero, print the version on standard output and exit.  */
63 bool show_version = false;
64
65 /* If nonzero, use null ciphers and skip all key exchanges. */
66 bool bypass_security = false;
67
68 /* If nonzero, disable swapping for this process. */
69 bool do_mlock = false;
70
71 /* If nonzero, chroot to netdir after startup. */
72 static bool do_chroot = false;
73
74 /* If !NULL, do setuid to given user after startup */
75 static const char *switchuser = NULL;
76
77 /* If nonzero, write log entries to a separate file. */
78 bool use_logfile = false;
79
80 char *identname = NULL;                         /* program name for syslog */
81 char *controlsocketname = NULL;                 /* control socket location */
82 char *logfilename = NULL;                       /* log file location */
83 char **g_argv;                                  /* a copy of the cmdline arguments */
84
85 static int status;
86
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         {"controlsocket", required_argument, NULL, 5},
100         {NULL, 0, NULL, 0}
101 };
102
103 #ifdef HAVE_MINGW
104 static struct WSAData wsa_state;
105 CRITICAL_SECTION mutex;
106 #endif
107
108 static void usage(bool status) {
109         if(status)
110                 fprintf(stderr, "Try `%s --help\' for more information.\n",
111                                 program_name);
112         else {
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                                 "      --controlsocket=FILENAME  Open control socket at 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");
126         }
127 }
128
129 static bool parse_options(int argc, char **argv) {
130         int r;
131         int option_index = 0;
132
133         while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
134                 switch (r) {
135                         case 0:                         /* long option */
136                                 break;
137
138                         case 'c':                               /* config file */
139                                 confbase = xstrdup(optarg);
140                                 break;
141
142                         case 'D':                               /* no detach */
143                                 do_detach = false;
144                                 break;
145
146                         case 'L':                               /* no detach */
147 #ifndef HAVE_MLOCKALL
148                                 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
149                                 return false;
150 #else
151                                 do_mlock = true;
152                                 break;
153 #endif
154
155                         case 'd':                               /* inc debug level */
156                                 if(optarg)
157                                         debug_level = atoi(optarg);
158                                 else
159                                         debug_level++;
160                                 break;
161
162                         case 'n':                               /* net name given */
163                                 netname = xstrdup(optarg);
164                                 break;
165
166                         case 'R':                               /* chroot to NETNAME dir */
167                                 do_chroot = true;
168                                 break;
169
170                         case 'U':                               /* setuid to USER */
171                                 switchuser = optarg;
172                                 break;
173
174                         case 1:                                 /* show help */
175                                 show_help = true;
176                                 break;
177
178                         case 2:                                 /* show version */
179                                 show_version = true;
180                                 break;
181
182                         case 3:                                 /* bypass security */
183                                 bypass_security = true;
184                                 break;
185
186                         case 4:                                 /* write log entries to a file */
187                                 use_logfile = true;
188                                 if(optarg)
189                                         logfilename = xstrdup(optarg);
190                                 break;
191
192                         case 5:                                 /* open control socket here */
193                                 controlsocketname = xstrdup(optarg);
194                                 break;
195
196                         case '?':
197                                 usage(true);
198                                 return false;
199
200                         default:
201                                 break;
202                 }
203         }
204
205         return true;
206 }
207
208 /*
209   Set all files and paths according to netname
210 */
211 static void make_names(void) {
212 #ifdef HAVE_MINGW
213         HKEY key;
214         char installdir[1024] = "";
215         long len = sizeof installdir;
216 #endif
217
218         if(netname)
219                 xasprintf(&identname, "tinc.%s", netname);
220         else
221                 identname = xstrdup("tinc");
222
223 #ifdef HAVE_MINGW
224         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
225                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
226                         if(!logfilename)
227                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
228                         if(!confbase) {
229                                 if(netname)
230                                         xasprintf(&confbase, "%s/%s", installdir, netname);
231                                 else
232                                         xasprintf(&confbase, "%s", installdir);
233                         }
234                 }
235                 RegCloseKey(key);
236                 if(*installdir)
237                         return;
238         }
239 #endif
240
241         if(!controlsocketname)
242                 xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
243
244         if(!logfilename)
245                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
246
247         if(netname) {
248                 if(!confbase)
249                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
250                 else
251                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
252         } else {
253                 if(!confbase)
254                         xasprintf(&confbase, CONFDIR "/tinc");
255         }
256 }
257
258 static void free_names() {
259         if (identname) free(identname);
260         if (netname) free(netname);
261         if (controlsocketname) free(controlsocketname);
262         if (logfilename) free(logfilename);
263         if (confbase) free(confbase);
264 }
265
266 static bool drop_privs() {
267 #ifdef HAVE_MINGW
268         if (switchuser) {
269                 logger(LOG_ERR, "%s not supported on this platform", "-U");
270                 return false;
271         }
272         if (do_chroot) {
273                 logger(LOG_ERR, "%s not supported on this platform", "-R");
274                 return false;
275         }
276 #else
277         uid_t uid = 0;
278         if (switchuser) {
279                 struct passwd *pw = getpwnam(switchuser);
280                 if (!pw) {
281                         logger(LOG_ERR, "unknown user `%s'", switchuser);
282                         return false;
283                 }
284                 uid = pw->pw_uid;
285                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
286                     setgid(pw->pw_gid) != 0) {
287                         logger(LOG_ERR, "System call `%s' failed: %s",
288                                "initgroups", strerror(errno));
289                         return false;
290                 }
291                 endgrent();
292                 endpwent();
293         }
294         if (do_chroot) {
295                 tzset();        /* for proper timestamps in logs */
296                 if (chroot(confbase) != 0 || chdir("/") != 0) {
297                         logger(LOG_ERR, "System call `%s' failed: %s",
298                                "chroot", strerror(errno));
299                         return false;
300                 }
301                 free(confbase);
302                 confbase = xstrdup("");
303         }
304         if (switchuser)
305                 if (setuid(uid) != 0) {
306                         logger(LOG_ERR, "System call `%s' failed: %s",
307                                "setuid", strerror(errno));
308                         return false;
309                 }
310 #endif
311         return true;
312 }
313
314 #ifdef HAVE_MINGW
315 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
316 #else
317 # define NORMAL_PRIORITY_CLASS 0
318 # define BELOW_NORMAL_PRIORITY_CLASS 10
319 # define HIGH_PRIORITY_CLASS -10
320 # define setpriority(level) nice(level)
321 #endif
322
323 int main(int argc, char **argv) {
324         program_name = argv[0];
325
326         if(!parse_options(argc, argv))
327                 return 1;
328         
329         make_names();
330
331         if(show_version) {
332                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
333                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
334                 printf("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
335                                 "See the AUTHORS file for a complete list.\n\n"
336                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
337                                 "and you are welcome to redistribute it under certain conditions;\n"
338                                 "see the file COPYING for details.\n");
339
340                 return 0;
341         }
342
343         if(show_help) {
344                 usage(false);
345                 return 0;
346         }
347
348         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
349
350         if(!event_init()) {
351                 logger(LOG_ERR, "Error initializing libevent!");
352                 return 1;
353         }
354
355         if(!init_control())
356                 return 1;
357
358         g_argv = argv;
359
360         init_configuration(&config_tree);
361
362         /* Slllluuuuuuurrrrp! */
363
364         srand(time(NULL));
365         crypto_init();
366
367         if(!read_server_config())
368                 return 1;
369
370         if(lzo_init() != LZO_E_OK) {
371                 logger(LOG_ERR, "Error initializing LZO compressor!");
372                 return 1;
373         }
374
375 #ifdef HAVE_MINGW
376         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
377                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
378                 return 1;
379         }
380
381         if(!do_detach || !init_service())
382                 return main2(argc, argv);
383         else
384                 return 1;
385 }
386
387 int main2(int argc, char **argv) {
388         InitializeCriticalSection(&mutex);
389         EnterCriticalSection(&mutex);
390 #endif
391
392         if(!detach())
393                 return 1;
394
395 #ifdef HAVE_MLOCKALL
396         /* Lock all pages into memory if requested.
397          * This has to be done after daemon()/fork() so it works for child.
398          * No need to do that in parent as it's very short-lived. */
399         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
400                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
401                    strerror(errno));
402                 return 1;
403         }
404 #endif
405
406         /* Setup sockets and open device. */
407
408         if(!setup_network())
409                 goto end;
410
411         /* Initiate all outgoing connections. */
412
413         try_outgoing_connections();
414
415         /* Change process priority */
416
417         char *priority = 0;
418
419         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
420                 if(!strcasecmp(priority, "Normal"))
421                         setpriority(NORMAL_PRIORITY_CLASS);
422                 else if(!strcasecmp(priority, "Low"))
423                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
424                 else if(!strcasecmp(priority, "High"))
425                         setpriority(HIGH_PRIORITY_CLASS);
426                 else {
427                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
428                         goto end;
429                 }
430         }
431
432         /* drop privileges */
433         if (!drop_privs())
434                 goto end;
435
436         /* Start main loop. It only exits when tinc is killed. */
437
438         status = main_loop();
439
440         /* Shutdown properly. */
441
442         ifdebug(CONNECTIONS)
443                 dump_device_stats();
444
445         close_network_connections();
446
447 end:
448         logger(LOG_NOTICE, "Terminating");
449
450 #ifndef HAVE_MINGW
451         exit_control();
452 #endif
453
454         crypto_exit();
455
456         exit_configuration(&config_tree);
457         free_names();
458
459         return status;
460 }