Free resources in rsa_t.
[oweals/tinc.git] / 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                   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 bool show_help = false;
71
72 /* If nonzero, print the version on standard output and exit.  */
73 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 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 *controlcookiename = NULL;
93 char **g_argv;                                  /* a copy of the cmdline arguments */
94
95 static int status;
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         {"controlcookie", required_argument, NULL, 5},
110         {NULL, 0, NULL, 0}
111 };
112
113 mutex_t mutex;
114
115 #ifdef HAVE_MINGW
116 static struct WSAData wsa_state;
117 CRITICAL_SECTION mutex;
118 int main2(int argc, char **argv);
119 #endif
120
121 static void usage(bool status) {
122         if(status)
123                 fprintf(stderr, "Try `%s --help\' for more information.\n",
124                                 program_name);
125         else {
126                 printf("Usage: %s [option]...\n\n", program_name);
127                 printf( "  -c, --config=DIR              Read configuration options from DIR.\n"
128                                 "  -D, --no-detach               Don't fork and detach.\n"
129                                 "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
130                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
131                                 "  -L, --mlock                   Lock tinc into main memory.\n"
132                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
133                                 "      --controlcookie=FILENAME  Write control socket cookie to FILENAME.\n"
134                                 "      --bypass-security         Disables meta protocol security, for debugging.\n"
135                                 "  -o [HOST.]KEY=VALUE           Set global/host configuration value.\n"
136                                 "  -R, --chroot                  chroot to NET dir at startup.\n"
137                                 "  -U, --user=USER               setuid to given USER at startup.\n"                            "      --help                    Display this help and exit.\n"
138                                 "      --version                 Output version information and exit.\n\n");
139                 printf("Report bugs to tinc@tinc-vpn.org.\n");
140         }
141 }
142
143 static bool parse_options(int argc, char **argv) {
144         config_t *cfg;
145         int r;
146         int option_index = 0;
147         int lineno = 0;
148
149         cmdline_conf = list_alloc((list_action_t)free_config);
150
151         while((r = getopt_long(argc, argv, "c:DLd::n:o:RU:", long_options, &option_index)) != EOF) {
152                 switch (r) {
153                         case 0:                         /* long option */
154                                 break;
155
156                         case 'c':                               /* config file */
157                                 confbase = xstrdup(optarg);
158                                 break;
159
160                         case 'D':                               /* no detach */
161                                 do_detach = false;
162                                 break;
163
164                         case 'L':                               /* no detach */
165 #ifndef HAVE_MLOCKALL
166                                 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
167                                 return false;
168 #else
169                                 do_mlock = true;
170                                 break;
171 #endif
172
173                         case 'd':                               /* inc debug level */
174                                 if(optarg)
175                                         debug_level = atoi(optarg);
176                                 else
177                                         debug_level++;
178                                 break;
179
180                         case 'n':                               /* net name given */
181                                 /* netname "." is special: a "top-level name" */
182                                 netname = strcmp(optarg, ".") != 0 ?
183                                                 xstrdup(optarg) : NULL;
184                                 break;
185
186                         case 'o':                               /* option */
187                                 cfg = parse_config_line(optarg, NULL, ++lineno);
188                                 if (!cfg)
189                                         return false;
190                                 list_insert_tail(cmdline_conf, cfg);
191                                 break;
192
193                         case 'R':                               /* chroot to NETNAME dir */
194                                 do_chroot = true;
195                                 break;
196
197                         case 'U':                               /* setuid to USER */
198                                 switchuser = optarg;
199                                 break;
200
201                         case 1:                                 /* show help */
202                                 show_help = true;
203                                 break;
204
205                         case 2:                                 /* show version */
206                                 show_version = true;
207                                 break;
208
209                         case 3:                                 /* bypass security */
210                                 bypass_security = true;
211                                 break;
212
213                         case 4:                                 /* write log entries to a file */
214                                 use_logfile = true;
215                                 if(optarg)
216                                         logfilename = xstrdup(optarg);
217                                 break;
218
219                         case 5:                                 /* open control socket here */
220                                 controlcookiename = xstrdup(optarg);
221                                 break;
222
223                         case '?':
224                                 usage(true);
225                                 return false;
226
227                         default:
228                                 break;
229                 }
230         }
231
232         return true;
233 }
234
235 /*
236   Set all files and paths according to netname
237 */
238 static void make_names(void) {
239 #ifdef HAVE_MINGW
240         HKEY key;
241         char installdir[1024] = "";
242         long len = sizeof installdir;
243 #endif
244
245         if(netname)
246                 xasprintf(&identname, "tinc.%s", netname);
247         else
248                 identname = xstrdup("tinc");
249
250 #ifdef HAVE_MINGW
251         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
252                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
253                         if(!logfilename)
254                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
255                         if(!confbase) {
256                                 if(netname)
257                                         xasprintf(&confbase, "%s/%s", installdir, netname);
258                                 else
259                                         xasprintf(&confbase, "%s", installdir);
260                         }
261                         if(!controlcookiename)
262                                 xasprintf(&controlcookiename, "%s/cookie", confbase);
263                 }
264                 RegCloseKey(key);
265                 if(*installdir)
266                         return;
267         }
268 #endif
269
270         if(!logfilename)
271                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
272
273         if(!controlcookiename)
274                 xasprintf(&controlcookiename, LOCALSTATEDIR "/run/%s.cookie", identname);
275
276         if(netname) {
277                 if(!confbase)
278                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
279                 else
280                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
281         } else {
282                 if(!confbase)
283                         xasprintf(&confbase, CONFDIR "/tinc");
284         }
285 }
286
287 static void free_names() {
288         if (identname) free(identname);
289         if (netname) free(netname);
290         if (controlcookiename) free(controlcookiename);
291         if (logfilename) free(logfilename);
292         if (confbase) free(confbase);
293 }
294
295 static bool drop_privs() {
296 #ifdef HAVE_MINGW
297         if (switchuser) {
298                 logger(LOG_ERR, "%s not supported on this platform", "-U");
299                 return false;
300         }
301         if (do_chroot) {
302                 logger(LOG_ERR, "%s not supported on this platform", "-R");
303                 return false;
304         }
305 #else
306         uid_t uid = 0;
307         if (switchuser) {
308                 struct passwd *pw = getpwnam(switchuser);
309                 if (!pw) {
310                         logger(LOG_ERR, "unknown user `%s'", switchuser);
311                         return false;
312                 }
313                 uid = pw->pw_uid;
314                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
315                     setgid(pw->pw_gid) != 0) {
316                         logger(LOG_ERR, "System call `%s' failed: %s",
317                                "initgroups", strerror(errno));
318                         return false;
319                 }
320                 endgrent();
321                 endpwent();
322         }
323         if (do_chroot) {
324                 tzset();        /* for proper timestamps in logs */
325                 if (chroot(confbase) != 0 || chdir("/") != 0) {
326                         logger(LOG_ERR, "System call `%s' failed: %s",
327                                "chroot", strerror(errno));
328                         return false;
329                 }
330                 free(confbase);
331                 confbase = xstrdup("");
332         }
333         if (switchuser)
334                 if (setuid(uid) != 0) {
335                         logger(LOG_ERR, "System call `%s' failed: %s",
336                                "setuid", strerror(errno));
337                         return false;
338                 }
339 #endif
340         return true;
341 }
342
343 #ifdef HAVE_MINGW
344 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
345 #else
346 # define NORMAL_PRIORITY_CLASS 0
347 # define BELOW_NORMAL_PRIORITY_CLASS 10
348 # define HIGH_PRIORITY_CLASS -10
349 # define setpriority(level) nice(level)
350 #endif
351
352 int main(int argc, char **argv) {
353         program_name = argv[0];
354
355         if(!parse_options(argc, argv))
356                 return 1;
357         
358         make_names();
359
360         if(show_version) {
361                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
362                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
363                 printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
364                                 "See the AUTHORS file for a complete list.\n\n"
365                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
366                                 "and you are welcome to redistribute it under certain conditions;\n"
367                                 "see the file COPYING for details.\n");
368
369                 return 0;
370         }
371
372         if(show_help) {
373                 usage(false);
374                 return 0;
375         }
376
377 #ifdef HAVE_MINGW
378         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
379                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
380                 return 1;
381         }
382 #endif
383
384         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
385
386         g_argv = argv;
387
388         mutex_create(&mutex);
389         mutex_lock(&mutex);
390         init_events();
391         init_configuration(&config_tree);
392
393         /* Slllluuuuuuurrrrp! */
394
395         srand(time(NULL));
396         crypto_init();
397
398         if(!read_server_config())
399                 return 1;
400
401 #ifdef HAVE_LZO
402         if(lzo_init() != LZO_E_OK) {
403                 logger(LOG_ERR, "Error initializing LZO compressor!");
404                 return 1;
405         }
406 #endif
407
408 #ifdef HAVE_MINGW
409         if(!do_detach || !init_service())
410                 return main2(argc, argv);
411         else
412                 return 1;
413 }
414
415 int main2(int argc, char **argv) {
416         InitializeCriticalSection(&mutex);
417         EnterCriticalSection(&mutex);
418 #endif
419
420         if(!detach())
421                 return 1;
422
423 #ifdef HAVE_MLOCKALL
424         /* Lock all pages into memory if requested.
425          * This has to be done after daemon()/fork() so it works for child.
426          * No need to do that in parent as it's very short-lived. */
427         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
428                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
429                    strerror(errno));
430                 return 1;
431         }
432 #endif
433
434         /* Setup sockets and open device. */
435
436         if(!setup_network())
437                 goto end;
438
439         if(!init_control())
440                 return 1;
441
442         /* Initiate all outgoing connections. */
443
444         try_outgoing_connections();
445
446         /* Change process priority */
447
448         char *priority = 0;
449
450         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
451                 if(!strcasecmp(priority, "Normal")) {
452                         if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
453                                 logger(LOG_ERR, "System call `%s' failed: %s",
454                                        "setpriority", strerror(errno));
455                                 goto end;
456                         }
457                 } else if(!strcasecmp(priority, "Low")) {
458                         if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
459                                        logger(LOG_ERR, "System call `%s' failed: %s",
460                                        "setpriority", strerror(errno));
461                                 goto end;
462                         }
463                 } else if(!strcasecmp(priority, "High")) {
464                         if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
465                                 logger(LOG_ERR, "System call `%s' failed: %s",
466                                        "setpriority", strerror(errno));
467                                 goto end;
468                         }
469                 } else {
470                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
471                         goto end;
472                 }
473         }
474
475         /* drop privileges */
476         if (!drop_privs())
477                 goto end;
478
479         /* Start main loop. It only exits when tinc is killed. */
480
481         status = main_loop();
482
483         /* Shutdown properly. */
484
485         ifdebug(CONNECTIONS)
486                 dump_device_stats();
487
488         close_network_connections();
489
490 end:
491         logger(LOG_NOTICE, "Terminating");
492
493         exit_control();
494
495         crypto_exit();
496
497         exit_configuration(&config_tree);
498         exit_events();
499         free_names();
500
501         return status;
502 }