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