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