Add --disable-lzo configure option
[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
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 #include "pidfile.h"
52
53 #include "conf.h"
54 #include "device.h"
55 #include "logger.h"
56 #include "net.h"
57 #include "netutl.h"
58 #include "process.h"
59 #include "protocol.h"
60 #include "utils.h"
61 #include "xalloc.h"
62
63 /* The name this program was run with. */
64 char *program_name = NULL;
65
66 /* If nonzero, display usage information and exit. */
67 bool show_help = false;
68
69 /* If nonzero, print the version on standard output and exit.  */
70 bool show_version = false;
71
72 /* If nonzero, it will attempt to kill a running tincd and exit. */
73 int kill_tincd = 0;
74
75 /* If nonzero, generate public/private keypair for this host/net. */
76 int generate_keys = 0;
77
78 /* If nonzero, use null ciphers and skip all key exchanges. */
79 bool bypass_security = false;
80
81 /* If nonzero, disable swapping for this process. */
82 bool do_mlock = false;
83
84 /* If nonzero, chroot to netdir after startup. */
85 static bool do_chroot = false;
86
87 /* If !NULL, do setuid to given user after startup */
88 static const char *switchuser = NULL;
89
90 /* If nonzero, write log entries to a separate file. */
91 bool use_logfile = false;
92
93 char *identname = NULL;                         /* program name for syslog */
94 char *pidfilename = NULL;                       /* pid file location */
95 char *logfilename = NULL;                       /* log file location */
96 char **g_argv;                                  /* a copy of the cmdline arguments */
97
98 static int status;
99
100 static struct option const long_options[] = {
101         {"config", required_argument, NULL, 'c'},
102         {"kill", optional_argument, NULL, 'k'},
103         {"net", required_argument, NULL, 'n'},
104         {"help", no_argument, NULL, 1},
105         {"version", no_argument, NULL, 2},
106         {"no-detach", no_argument, NULL, 'D'},
107         {"generate-keys", optional_argument, NULL, 'K'},
108         {"debug", optional_argument, NULL, 'd'},
109         {"bypass-security", no_argument, NULL, 3},
110         {"mlock", no_argument, NULL, 'L'},
111         {"chroot", no_argument, NULL, 'R'},
112         {"user", required_argument, NULL, 'U'},
113         {"logfile", optional_argument, NULL, 4},
114         {"pidfile", required_argument, NULL, 5},
115         {NULL, 0, NULL, 0}
116 };
117
118 #ifdef HAVE_MINGW
119 static struct WSAData wsa_state;
120 CRITICAL_SECTION mutex;
121 #endif
122
123 static void usage(bool status) {
124         if(status)
125                 fprintf(stderr, "Try `%s --help\' for more information.\n",
126                                 program_name);
127         else {
128                 printf("Usage: %s [option]...\n\n", program_name);
129                 printf("  -c, --config=DIR           Read configuration options from DIR.\n"
130                                 "  -D, --no-detach            Don't fork and detach.\n"
131                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
132                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
133                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
134                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
135                                 "  -L, --mlock                Lock tinc into main memory.\n"
136                                 "      --logfile[=FILENAME]   Write log entries to a logfile.\n"
137                                 "      --pidfile=FILENAME     Write PID to FILENAME.\n"
138                                 "  -R, --chroot               chroot to NET dir at startup.\n"
139                                 "  -U, --user=USER            setuid to given USER at startup.\n"
140                                 "      --help                 Display this help and exit.\n"
141                                 "      --version              Output version information and exit.\n\n");
142                 printf("Report bugs to tinc@tinc-vpn.org.\n");
143         }
144 }
145
146 static bool parse_options(int argc, char **argv) {
147         int r;
148         int option_index = 0;
149
150         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::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(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 'k':                               /* kill old tincds */
180 #ifndef HAVE_MINGW
181                                 if(optarg) {
182                                         if(!strcasecmp(optarg, "HUP"))
183                                                 kill_tincd = SIGHUP;
184                                         else if(!strcasecmp(optarg, "TERM"))
185                                                 kill_tincd = SIGTERM;
186                                         else if(!strcasecmp(optarg, "KILL"))
187                                                 kill_tincd = SIGKILL;
188                                         else if(!strcasecmp(optarg, "USR1"))
189                                                 kill_tincd = SIGUSR1;
190                                         else if(!strcasecmp(optarg, "USR2"))
191                                                 kill_tincd = SIGUSR2;
192                                         else if(!strcasecmp(optarg, "WINCH"))
193                                                 kill_tincd = SIGWINCH;
194                                         else if(!strcasecmp(optarg, "INT"))
195                                                 kill_tincd = SIGINT;
196                                         else if(!strcasecmp(optarg, "ALRM"))
197                                                 kill_tincd = SIGALRM;
198                                         else {
199                                                 kill_tincd = atoi(optarg);
200
201                                                 if(!kill_tincd) {
202                                                         fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
203                                                                         optarg);
204                                                         usage(true);
205                                                         return false;
206                                                 }
207                                         }
208                                 } else
209                                         kill_tincd = SIGTERM;
210 #else
211                                         kill_tincd = 1;
212 #endif
213                                 break;
214
215                         case 'n':                               /* net name given */
216                                 netname = xstrdup(optarg);
217                                 break;
218
219                         case 'K':                               /* generate public/private keypair */
220                                 if(optarg) {
221                                         generate_keys = atoi(optarg);
222
223                                         if(generate_keys < 512) {
224                                                 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
225                                                                 optarg);
226                                                 usage(true);
227                                                 return false;
228                                         }
229
230                                         generate_keys &= ~7;    /* Round it to bytes */
231                                 } else
232                                         generate_keys = 2048;
233                                 break;
234
235                         case 'R':                               /* chroot to NETNAME dir */
236                                 do_chroot = true;
237                                 break;
238
239                         case 'U':                               /* setuid to USER */
240                                 switchuser = optarg;
241                                 break;
242
243                         case 1:                                 /* show help */
244                                 show_help = true;
245                                 break;
246
247                         case 2:                                 /* show version */
248                                 show_version = true;
249                                 break;
250
251                         case 3:                                 /* bypass security */
252                                 bypass_security = true;
253                                 break;
254
255                         case 4:                                 /* write log entries to a file */
256                                 use_logfile = true;
257                                 if(optarg)
258                                         logfilename = xstrdup(optarg);
259                                 break;
260
261                         case 5:                                 /* write PID to a file */
262                                 pidfilename = xstrdup(optarg);
263                                 break;
264
265                         case '?':
266                                 usage(true);
267                                 return false;
268
269                         default:
270                                 break;
271                 }
272         }
273
274         return true;
275 }
276
277 /* This function prettyprints the key generation process */
278
279 static void indicator(int a, int b, void *p) {
280         switch (a) {
281                 case 0:
282                         fprintf(stderr, ".");
283                         break;
284
285                 case 1:
286                         fprintf(stderr, "+");
287                         break;
288
289                 case 2:
290                         fprintf(stderr, "-");
291                         break;
292
293                 case 3:
294                         switch (b) {
295                                 case 0:
296                                         fprintf(stderr, " p\n");
297                                         break;
298
299                                 case 1:
300                                         fprintf(stderr, " q\n");
301                                         break;
302
303                                 default:
304                                         fprintf(stderr, "?");
305                         }
306                         break;
307
308                 default:
309                         fprintf(stderr, "?");
310         }
311 }
312
313 /*
314   Generate a public/private RSA keypair, and ask for a file to store
315   them in.
316 */
317 static bool keygen(int bits) {
318         RSA *rsa_key;
319         FILE *f;
320         char *name = NULL;
321         char *filename;
322
323         get_config_string(lookup_config(config_tree, "Name"), &name);
324
325         if(name && !check_id(name)) {
326                 fprintf(stderr, "Invalid name for myself!\n");
327                 return false;
328         }
329
330         fprintf(stderr, "Generating %d bits keys:\n", bits);
331         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
332
333         if(!rsa_key) {
334                 fprintf(stderr, "Error during key generation!\n");
335                 return false;
336         } else
337                 fprintf(stderr, "Done.\n");
338
339         xasprintf(&filename, "%s/rsa_key.priv", confbase);
340         f = ask_and_open(filename, "private RSA key");
341
342         if(!f)
343                 return false;
344
345         if(disable_old_keys(f))
346                 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
347   
348 #ifdef HAVE_FCHMOD
349         /* Make it unreadable for others. */
350         fchmod(fileno(f), 0600);
351 #endif
352                 
353         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
354         fclose(f);
355         free(filename);
356
357         if(name)
358                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
359         else
360                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
361
362         f = ask_and_open(filename, "public RSA key");
363
364         if(!f)
365                 return false;
366
367         if(disable_old_keys(f))
368                 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
369
370         PEM_write_RSAPublicKey(f, rsa_key);
371         fclose(f);
372         free(filename);
373         if(name)
374                 free(name);
375
376         return true;
377 }
378
379 /*
380   Set all files and paths according to netname
381 */
382 static void make_names(void) {
383 #ifdef HAVE_MINGW
384         HKEY key;
385         char installdir[1024] = "";
386         long len = sizeof(installdir);
387 #endif
388
389         if(netname)
390                 xasprintf(&identname, "tinc.%s", netname);
391         else
392                 identname = xstrdup("tinc");
393
394 #ifdef HAVE_MINGW
395         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
396                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
397                         if(!logfilename)
398                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
399                         if(!confbase) {
400                                 if(netname)
401                                         xasprintf(&confbase, "%s/%s", installdir, netname);
402                                 else
403                                         xasprintf(&confbase, "%s", installdir);
404                         }
405                 }
406                 RegCloseKey(key);
407                 if(*installdir)
408                         return;
409         }
410 #endif
411
412         if(!pidfilename)
413                 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
414
415         if(!logfilename)
416                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
417
418         if(netname) {
419                 if(!confbase)
420                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
421                 else
422                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
423         } else {
424                 if(!confbase)
425                         xasprintf(&confbase, CONFDIR "/tinc");
426         }
427 }
428
429 static void free_names() {
430         if (identname) free(identname);
431         if (netname) free(netname);
432         if (pidfilename) free(pidfilename);
433         if (logfilename) free(logfilename);
434         if (confbase) free(confbase);
435 }
436
437 static bool drop_privs() {
438 #ifdef HAVE_MINGW
439         if (switchuser) {
440                 logger(LOG_ERR, "%s not supported on this platform", "-U");
441                 return false;
442         }
443         if (do_chroot) {
444                 logger(LOG_ERR, "%s not supported on this platform", "-R");
445                 return false;
446         }
447 #else
448         uid_t uid = 0;
449         if (switchuser) {
450                 struct passwd *pw = getpwnam(switchuser);
451                 if (!pw) {
452                         logger(LOG_ERR, "unknown user `%s'", switchuser);
453                         return false;
454                 }
455                 uid = pw->pw_uid;
456                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
457                     setgid(pw->pw_gid) != 0) {
458                         logger(LOG_ERR, "System call `%s' failed: %s",
459                                "initgroups", strerror(errno));
460                         return false;
461                 }
462                 endgrent();
463                 endpwent();
464         }
465         if (do_chroot) {
466                 tzset();        /* for proper timestamps in logs */
467                 if (chroot(confbase) != 0 || chdir("/") != 0) {
468                         logger(LOG_ERR, "System call `%s' failed: %s",
469                                "chroot", strerror(errno));
470                         return false;
471                 }
472                 free(confbase);
473                 confbase = xstrdup("");
474         }
475         if (switchuser)
476                 if (setuid(uid) != 0) {
477                         logger(LOG_ERR, "System call `%s' failed: %s",
478                                "setuid", strerror(errno));
479                         return false;
480                 }
481 #endif
482         return true;
483 }
484
485 #ifdef HAVE_MINGW
486 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
487 #else
488 # define NORMAL_PRIORITY_CLASS 0
489 # define BELOW_NORMAL_PRIORITY_CLASS 10
490 # define HIGH_PRIORITY_CLASS -10
491 # define setpriority(level) nice(level)
492 #endif
493
494 int main(int argc, char **argv) {
495         program_name = argv[0];
496
497         if(!parse_options(argc, argv))
498                 return 1;
499         
500         make_names();
501
502         if(show_version) {
503                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
504                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
505                 printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
506                                 "See the AUTHORS file for a complete list.\n\n"
507                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
508                                 "and you are welcome to redistribute it under certain conditions;\n"
509                                 "see the file COPYING for details.\n");
510
511                 return 0;
512         }
513
514         if(show_help) {
515                 usage(false);
516                 return 0;
517         }
518
519         if(kill_tincd)
520                 return !kill_other(kill_tincd);
521
522         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
523
524         g_argv = argv;
525
526         init_configuration(&config_tree);
527
528         /* Slllluuuuuuurrrrp! */
529
530         RAND_load_file("/dev/urandom", 1024);
531
532         ENGINE_load_builtin_engines();
533         ENGINE_register_all_complete();
534
535         OpenSSL_add_all_algorithms();
536
537         if(generate_keys) {
538                 read_server_config();
539                 return !keygen(generate_keys);
540         }
541
542         if(!read_server_config())
543                 return 1;
544
545 #ifdef HAVE_LZO
546         if(lzo_init() != LZO_E_OK) {
547                 logger(LOG_ERR, "Error initializing LZO compressor!");
548                 return 1;
549         }
550 #endif
551
552 #ifdef HAVE_MINGW
553         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
554                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
555                 return 1;
556         }
557
558         if(!do_detach || !init_service())
559                 return main2(argc, argv);
560         else
561                 return 1;
562 }
563
564 int main2(int argc, char **argv) {
565         InitializeCriticalSection(&mutex);
566         EnterCriticalSection(&mutex);
567 #endif
568
569         if(!detach())
570                 return 1;
571
572 #ifdef HAVE_MLOCKALL
573         /* Lock all pages into memory if requested.
574          * This has to be done after daemon()/fork() so it works for child.
575          * No need to do that in parent as it's very short-lived. */
576         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
577                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
578                    strerror(errno));
579                 return 1;
580         }
581 #endif
582
583         /* Setup sockets and open device. */
584
585         if(!setup_network())
586                 goto end;
587
588         /* Initiate all outgoing connections. */
589
590         try_outgoing_connections();
591
592         /* Change process priority */
593
594         char *priority = 0;
595
596         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
597                 if(!strcasecmp(priority, "Normal"))
598                         setpriority(NORMAL_PRIORITY_CLASS);
599                 else if(!strcasecmp(priority, "Low"))
600                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
601                 else if(!strcasecmp(priority, "High"))
602                         setpriority(HIGH_PRIORITY_CLASS);
603                 else {
604                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
605                         goto end;
606                 }
607         }
608
609         /* drop privileges */
610         if (!drop_privs())
611                 goto end;
612
613         /* Start main loop. It only exits when tinc is killed. */
614
615         status = main_loop();
616
617         /* Shutdown properly. */
618
619         ifdebug(CONNECTIONS)
620                 dump_device_stats();
621
622         close_network_connections();
623
624 end:
625         logger(LOG_NOTICE, "Terminating");
626
627 #ifndef HAVE_MINGW
628         remove_pid(pidfilename);
629 #endif
630
631         EVP_cleanup();
632         ENGINE_cleanup();
633         CRYPTO_cleanup_all_ex_data();
634         ERR_remove_state(0);
635         ERR_free_strings();
636
637         exit_configuration(&config_tree);
638         free_names();
639
640         return status;
641 }