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