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