e1eb3b3d471933b91bbf335d471bab754ceacd74
[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 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                                 "  -R, --chroot               chroot to NET dir at startup.\n"
140                                 "  -U, --user=USER            setuid to given USER at startup.\n"
141                                 "      --help                 Display this help and exit.\n"
142                                 "      --version              Output version information and exit.\n\n");
143                 printf("Report bugs to tinc@tinc-vpn.org.\n");
144         }
145 }
146
147 static bool parse_options(int argc, char **argv) {
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         switch (a) {
282                 case 0:
283                         fprintf(stderr, ".");
284                         break;
285
286                 case 1:
287                         fprintf(stderr, "+");
288                         break;
289
290                 case 2:
291                         fprintf(stderr, "-");
292                         break;
293
294                 case 3:
295                         switch (b) {
296                                 case 0:
297                                         fprintf(stderr, " p\n");
298                                         break;
299
300                                 case 1:
301                                         fprintf(stderr, " q\n");
302                                         break;
303
304                                 default:
305                                         fprintf(stderr, "?");
306                         }
307                         break;
308
309                 default:
310                         fprintf(stderr, "?");
311         }
312 }
313
314 /*
315   Generate a public/private RSA keypair, and ask for a file to store
316   them in.
317 */
318 static bool keygen(int bits) {
319         RSA *rsa_key;
320         FILE *f;
321         char *name = NULL;
322         char *filename;
323
324         get_config_string(lookup_config(config_tree, "Name"), &name);
325
326         if(name && !check_id(name)) {
327                 fprintf(stderr, "Invalid name for myself!\n");
328                 return false;
329         }
330
331         fprintf(stderr, "Generating %d bits keys:\n", bits);
332         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
333
334         if(!rsa_key) {
335                 fprintf(stderr, "Error during key generation!\n");
336                 return false;
337         } else
338                 fprintf(stderr, "Done.\n");
339
340         xasprintf(&filename, "%s/rsa_key.priv", confbase);
341         f = ask_and_open(filename, "private RSA key");
342
343         if(!f)
344                 return false;
345
346         if(disable_old_keys(f))
347                 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
348   
349 #ifdef HAVE_FCHMOD
350         /* Make it unreadable for others. */
351         fchmod(fileno(f), 0600);
352 #endif
353                 
354         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
355         fclose(f);
356         free(filename);
357
358         if(name)
359                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
360         else
361                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
362
363         f = ask_and_open(filename, "public RSA key");
364
365         if(!f)
366                 return false;
367
368         if(disable_old_keys(f))
369                 fprintf(stderr, "Warning: old key(s) found and disabled.\n");
370
371         PEM_write_RSAPublicKey(f, rsa_key);
372         fclose(f);
373         free(filename);
374         if(name)
375                 free(name);
376
377         return true;
378 }
379
380 /*
381   Set all files and paths according to netname
382 */
383 static void make_names(void) {
384 #ifdef HAVE_MINGW
385         HKEY key;
386         char installdir[1024] = "";
387         long len = sizeof(installdir);
388 #endif
389
390         if(netname)
391                 xasprintf(&identname, "tinc.%s", netname);
392         else
393                 identname = xstrdup("tinc");
394
395 #ifdef HAVE_MINGW
396         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
397                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
398                         if(!logfilename)
399                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
400                         if(!confbase) {
401                                 if(netname)
402                                         xasprintf(&confbase, "%s/%s", installdir, netname);
403                                 else
404                                         xasprintf(&confbase, "%s", installdir);
405                         }
406                 }
407                 RegCloseKey(key);
408                 if(*installdir)
409                         return;
410         }
411 #endif
412
413         if(!pidfilename)
414                 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
415
416         if(!logfilename)
417                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
418
419         if(netname) {
420                 if(!confbase)
421                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
422                 else
423                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
424         } else {
425                 if(!confbase)
426                         xasprintf(&confbase, CONFDIR "/tinc");
427         }
428 }
429
430 static void free_names() {
431         if (identname) free(identname);
432         if (netname) free(netname);
433         if (pidfilename) free(pidfilename);
434         if (logfilename) free(logfilename);
435         if (confbase) free(confbase);
436 }
437
438 static bool drop_privs() {
439 #ifdef HAVE_MINGW
440         if (switchuser) {
441                 logger(LOG_ERR, "%s not supported on this platform", "-U");
442                 return false;
443         }
444         if (do_chroot) {
445                 logger(LOG_ERR, "%s not supported on this platform", "-R");
446                 return false;
447         }
448 #else
449         uid_t uid = 0;
450         if (switchuser) {
451                 struct passwd *pw = getpwnam(switchuser);
452                 if (!pw) {
453                         logger(LOG_ERR, "unknown user `%s'", switchuser);
454                         return false;
455                 }
456                 uid = pw->pw_uid;
457                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
458                     setgid(pw->pw_gid) != 0) {
459                         logger(LOG_ERR, "System call `%s' failed: %s",
460                                "initgroups", strerror(errno));
461                         return false;
462                 }
463                 endgrent();
464                 endpwent();
465         }
466         if (do_chroot) {
467                 tzset();        /* for proper timestamps in logs */
468                 if (chroot(confbase) != 0 || chdir("/") != 0) {
469                         logger(LOG_ERR, "System call `%s' failed: %s",
470                                "chroot", strerror(errno));
471                         return false;
472                 }
473                 free(confbase);
474                 confbase = xstrdup("");
475         }
476         if (switchuser)
477                 if (setuid(uid) != 0) {
478                         logger(LOG_ERR, "System call `%s' failed: %s",
479                                "setuid", strerror(errno));
480                         return false;
481                 }
482 #endif
483         return true;
484 }
485
486 #ifdef HAVE_MINGW
487 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
488 #else
489 # define NORMAL_PRIORITY_CLASS 0
490 # define BELOW_NORMAL_PRIORITY_CLASS 10
491 # define HIGH_PRIORITY_CLASS -10
492 # define setpriority(level) nice(level)
493 #endif
494
495 int main(int argc, char **argv) {
496         program_name = argv[0];
497
498         if(!parse_options(argc, argv))
499                 return 1;
500         
501         make_names();
502
503         if(show_version) {
504                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
505                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
506                 printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
507                                 "See the AUTHORS file for a complete list.\n\n"
508                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
509                                 "and you are welcome to redistribute it under certain conditions;\n"
510                                 "see the file COPYING for details.\n");
511
512                 return 0;
513         }
514
515         if(show_help) {
516                 usage(false);
517                 return 0;
518         }
519
520         if(kill_tincd)
521                 return !kill_other(kill_tincd);
522
523         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
524
525         g_argv = argv;
526
527         init_configuration(&config_tree);
528
529         /* Slllluuuuuuurrrrp! */
530
531         RAND_load_file("/dev/urandom", 1024);
532
533         ENGINE_load_builtin_engines();
534         ENGINE_register_all_complete();
535
536         OpenSSL_add_all_algorithms();
537
538         if(generate_keys) {
539                 read_server_config();
540                 return !keygen(generate_keys);
541         }
542
543         if(!read_server_config())
544                 return 1;
545
546 #ifdef HAVE_LZO
547         if(lzo_init() != LZO_E_OK) {
548                 logger(LOG_ERR, "Error initializing LZO compressor!");
549                 return 1;
550         }
551 #endif
552
553 #ifdef HAVE_MINGW
554         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
555                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
556                 return 1;
557         }
558
559         if(!do_detach || !init_service())
560                 return main2(argc, argv);
561         else
562                 return 1;
563 }
564
565 int main2(int argc, char **argv) {
566         InitializeCriticalSection(&mutex);
567         EnterCriticalSection(&mutex);
568 #endif
569
570         if(!detach())
571                 return 1;
572
573 #ifdef HAVE_MLOCKALL
574         /* Lock all pages into memory if requested.
575          * This has to be done after daemon()/fork() so it works for child.
576          * No need to do that in parent as it's very short-lived. */
577         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
578                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
579                    strerror(errno));
580                 return 1;
581         }
582 #endif
583
584         /* Setup sockets and open device. */
585
586         if(!setup_network())
587                 goto end;
588
589         /* Initiate all outgoing connections. */
590
591         try_outgoing_connections();
592
593         /* Change process priority */
594
595         char *priority = 0;
596
597         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
598                 if(!strcasecmp(priority, "Normal"))
599                         setpriority(NORMAL_PRIORITY_CLASS);
600                 else if(!strcasecmp(priority, "Low"))
601                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
602                 else if(!strcasecmp(priority, "High"))
603                         setpriority(HIGH_PRIORITY_CLASS);
604                 else {
605                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
606                         goto end;
607                 }
608         }
609
610         /* drop privileges */
611         if (!drop_privs())
612                 goto end;
613
614         /* Start main loop. It only exits when tinc is killed. */
615
616         status = main_loop();
617
618         /* Shutdown properly. */
619
620         ifdebug(CONNECTIONS)
621                 dump_device_stats();
622
623         close_network_connections();
624
625 end:
626         logger(LOG_NOTICE, "Terminating");
627
628 #ifndef HAVE_MINGW
629         remove_pid(pidfilename);
630 #endif
631
632         EVP_cleanup();
633         ENGINE_cleanup();
634         CRYPTO_cleanup_all_ex_data();
635         ERR_remove_state(0);
636         ERR_free_strings();
637
638         exit_configuration(&config_tree);
639         free_names();
640
641         return status;
642 }