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