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