edb03f51993bbfc282164639693537e59e6ae2b4
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2022 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_LZO
33 #include LZO1X_H
34 #endif
35
36 #ifdef HAVE_LZ4
37 #include <lz4.h>
38 #endif
39
40 #ifndef HAVE_WINDOWS
41 #include <pwd.h>
42 #include <grp.h>
43 #include <time.h>
44 #endif
45
46 #include "conf.h"
47 #include "crypto.h"
48 #include "event.h"
49 #include "logger.h"
50 #include "names.h"
51 #include "net.h"
52 #include "process.h"
53 #include "protocol.h"
54 #include "utils.h"
55 #include "xalloc.h"
56 #include "version.h"
57 #include "random.h"
58
59 /* If nonzero, display usage information and exit. */
60 static bool show_help = false;
61
62 /* If nonzero, print the version on standard output and exit.  */
63 static bool show_version = false;
64
65 #ifdef HAVE_MLOCKALL
66 /* If nonzero, disable swapping for this process. */
67 static bool do_mlock = false;
68 #endif
69
70 #ifndef HAVE_WINDOWS
71 /* If nonzero, chroot to netdir after startup. */
72 static bool do_chroot = false;
73
74 /* If !NULL, do setuid to given user after startup */
75 static const char *switchuser = NULL;
76 #endif
77
78 char **g_argv;                  /* a copy of the cmdline arguments */
79
80 static int status = 1;
81
82 typedef enum option_t {
83         OPT_BAD_OPTION  = '?',
84         OPT_LONG_OPTION =  0,
85
86         // Short options
87         OPT_CONFIG_FILE = 'c',
88         OPT_NETNAME     = 'n',
89         OPT_NO_DETACH   = 'D',
90         OPT_DEBUG       = 'd',
91         OPT_MLOCK       = 'L',
92         OPT_CHROOT      = 'R',
93         OPT_CHANGE_USER = 'U',
94         OPT_SYSLOG      = 's',
95         OPT_OPTION      = 'o',
96
97         // Long options
98         OPT_HELP        = 255,
99         OPT_VERSION,
100         OPT_NO_SECURITY,
101         OPT_LOGFILE,
102         OPT_PIDFILE,
103 } option_t;
104
105 static struct option const long_options[] = {
106         {"config",          required_argument, NULL, OPT_CONFIG_FILE},
107         {"net",             required_argument, NULL, OPT_NETNAME},
108         {"no-detach",       no_argument,       NULL, OPT_NO_DETACH},
109         {"debug",           optional_argument, NULL, OPT_DEBUG},
110         {"mlock",           no_argument,       NULL, OPT_MLOCK},
111         {"chroot",          no_argument,       NULL, OPT_CHROOT},
112         {"user",            required_argument, NULL, OPT_CHANGE_USER},
113         {"syslog",          no_argument,       NULL, OPT_SYSLOG},
114         {"option",          required_argument, NULL, OPT_OPTION},
115         {"help",            no_argument,       NULL, OPT_HELP},
116         {"version",         no_argument,       NULL, OPT_VERSION},
117         {"bypass-security", no_argument,       NULL, OPT_NO_SECURITY},
118         {"logfile",         optional_argument, NULL, OPT_LOGFILE},
119         {"pidfile",         required_argument, NULL, OPT_PIDFILE},
120         {NULL,              0,                 NULL, 0},
121 };
122
123 #ifdef HAVE_WINDOWS
124 static struct WSAData wsa_state;
125 int main2(int argc, char **argv);
126 #endif
127
128 static void usage(bool status) {
129         if(status)
130                 fprintf(stderr, "Try `%s --help\' for more information.\n",
131                         program_name);
132         else {
133                 fprintf(stdout,
134                         "Usage: %s [option]...\n"
135                         "\n"
136                         "  -c, --config=DIR              Read configuration options from DIR.\n"
137                         "  -D, --no-detach               Don't fork and detach.\n"
138                         "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
139                         "  -n, --net=NETNAME             Connect to net NETNAME.\n"
140 #ifdef HAVE_MLOCKALL
141                         "  -L, --mlock                   Lock tinc into main memory.\n"
142 #endif
143                         "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
144                         "  -s  --syslog                  Use syslog instead of stderr with --no-detach.\n"
145                         "      --pidfile=FILENAME        Write PID and control socket cookie to FILENAME.\n"
146                         "      --bypass-security         Disables meta protocol security, for debugging.\n"
147                         "  -o, --option[HOST.]KEY=VALUE  Set global/host configuration value.\n"
148 #ifndef HAVE_WINDOWS
149                         "  -R, --chroot                  chroot to NET dir at startup.\n"
150                         "  -U, --user=USER               setuid to given USER at startup.\n"
151 #endif
152                         "      --help                    Display this help and exit.\n"
153                         "      --version                 Output version information and exit.\n"
154                         "\n"
155                         "Report bugs to tinc@tinc-vpn.org.\n",
156                         program_name);
157         }
158 }
159
160 // Try to resolve path to absolute, return a copy of the argument if this fails.
161 static char *get_path_arg(char *arg) {
162         char *result = absolute_path(arg);
163
164         if(!result) {
165                 result = xstrdup(arg);
166         }
167
168         return result;
169 }
170
171 static bool parse_options(int argc, char **argv) {
172         config_t *cfg;
173         int r;
174         int option_index = 0;
175         int lineno = 0;
176
177         while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
178                 switch((option_t) r) {
179                 case OPT_LONG_OPTION:
180                         break;
181
182                 case OPT_BAD_OPTION:
183                         usage(true);
184                         goto exit_fail;
185
186                 case OPT_CONFIG_FILE:
187                         free(confbase);
188                         confbase = get_path_arg(optarg);
189                         break;
190
191                 case OPT_NO_DETACH:
192                         do_detach = false;
193                         break;
194
195                 case OPT_MLOCK: /* lock tincd into RAM */
196 #ifndef HAVE_MLOCKALL
197                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
198                         goto exit_fail;
199 #else
200                         do_mlock = true;
201                         break;
202 #endif
203
204                 case OPT_DEBUG: /* increase debug level */
205                         if(!optarg && optind < argc && *argv[optind] != '-') {
206                                 optarg = argv[optind++];
207                         }
208
209                         if(optarg) {
210                                 debug_level = atoi(optarg);
211                         } else {
212                                 debug_level++;
213                         }
214
215                         break;
216
217                 case OPT_NETNAME:
218                         free(netname);
219                         netname = xstrdup(optarg);
220                         break;
221
222                 case OPT_SYSLOG:
223                         use_logfile = false;
224                         use_syslog = true;
225                         break;
226
227                 case OPT_OPTION:
228                         cfg = parse_config_line(optarg, NULL, ++lineno);
229
230                         if(!cfg) {
231                                 goto exit_fail;
232                         }
233
234                         list_insert_tail(&cmdline_conf, cfg);
235                         break;
236
237 #ifdef HAVE_WINDOWS
238
239                 case OPT_CHANGE_USER:
240                 case OPT_CHROOT:
241                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
242                         goto exit_fail;
243 #else
244
245                 case OPT_CHROOT:
246                         do_chroot = true;
247                         break;
248
249                 case OPT_CHANGE_USER:
250                         switchuser = optarg;
251                         break;
252 #endif
253
254                 case OPT_HELP:
255                         show_help = true;
256                         break;
257
258                 case OPT_VERSION:
259                         show_version = true;
260                         break;
261
262                 case OPT_NO_SECURITY:
263                         bypass_security = true;
264                         break;
265
266                 case OPT_LOGFILE:
267                         use_syslog = false;
268                         use_logfile = true;
269
270                         if(!optarg && optind < argc && *argv[optind] != '-') {
271                                 optarg = argv[optind++];
272                         }
273
274                         if(optarg) {
275                                 free(logfilename);
276                                 logfilename = get_path_arg(optarg);
277                         }
278
279                         break;
280
281                 case OPT_PIDFILE:
282                         free(pidfilename);
283                         pidfilename = get_path_arg(optarg);
284                         break;
285
286                 default:
287                         break;
288                 }
289         }
290
291         if(optind < argc) {
292                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
293                 usage(true);
294                 goto exit_fail;
295         }
296
297         if(!netname && (netname = getenv("NETNAME"))) {
298                 netname = xstrdup(netname);
299         }
300
301         /* netname "." is special: a "top-level name" */
302
303         if(netname && (!*netname || !strcmp(netname, "."))) {
304                 free(netname);
305                 netname = NULL;
306         }
307
308         if(netname && !check_netname(netname, false)) {
309                 fprintf(stderr, "Invalid character in netname!\n");
310                 goto exit_fail;
311         }
312
313         if(netname && !check_netname(netname, true)) {
314                 fprintf(stderr, "Warning: unsafe character in netname!\n");
315         }
316
317         return true;
318
319 exit_fail:
320         free_names();
321         list_empty_list(&cmdline_conf);
322         return false;
323 }
324
325 static bool drop_privs(void) {
326 #ifndef HAVE_WINDOWS
327         uid_t uid = 0;
328
329         if(switchuser) {
330                 struct passwd *pw = getpwnam(switchuser);
331
332                 if(!pw) {
333                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
334                         return false;
335                 }
336
337                 uid = pw->pw_uid;
338
339                 // The second parameter to initgroups on macOS requires int,
340                 // but __gid_t is unsigned int. There's not much we can do here.
341                 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
342                                 setgid(pw->pw_gid) != 0) {
343                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
344                                "initgroups", strerror(errno));
345                         return false;
346                 }
347
348 #ifndef __ANDROID__
349 // Not supported in android NDK
350                 endgrent();
351                 endpwent();
352 #endif
353         }
354
355         if(do_chroot) {
356                 tzset();        /* for proper timestamps in logs */
357
358                 if(chroot(confbase) != 0 || chdir("/") != 0) {
359                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
360                                "chroot", strerror(errno));
361                         return false;
362                 }
363
364                 free(confbase);
365                 confbase = xstrdup("");
366         }
367
368         if(switchuser)
369                 if(setuid(uid) != 0) {
370                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
371                                "setuid", strerror(errno));
372                         return false;
373                 }
374
375 #endif
376         return true;
377 }
378
379 #ifdef HAVE_WINDOWS
380 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
381
382 static void stop_handler(void *data, int flags) {
383         (void)data;
384         (void)flags;
385
386         event_exit();
387 }
388
389 static BOOL WINAPI console_ctrl_handler(DWORD type) {
390         (void)type;
391
392         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
393
394         if(WSASetEvent(stop_io.event) == FALSE) {
395                 abort();
396         }
397
398         return TRUE;
399 }
400 #else
401 # define NORMAL_PRIORITY_CLASS 0
402 # define BELOW_NORMAL_PRIORITY_CLASS 10
403 # define HIGH_PRIORITY_CLASS -10
404 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
405 #endif
406
407 static void cleanup(void) {
408         splay_empty_tree(&config_tree);
409         list_empty_list(&cmdline_conf);
410         free_names();
411 }
412
413 int main(int argc, char **argv) {
414         program_name = argv[0];
415
416         if(!parse_options(argc, argv)) {
417                 return 1;
418         }
419
420         if(show_version) {
421                 fprintf(stdout,
422                         "%s version %s (built %s %s, protocol %d.%d)\n"
423                         "Features:"
424 #ifdef HAVE_OPENSSL
425                         " openssl"
426 #endif
427 #ifdef HAVE_LIBGCRYPT
428                         " libgcrypt"
429 #endif
430 #ifdef HAVE_LZO
431                         " comp_lzo"
432 #endif
433 #ifdef HAVE_ZLIB
434                         " comp_zlib"
435 #endif
436 #ifdef HAVE_LZ4
437                         " comp_lz4"
438 #endif
439 #ifndef DISABLE_LEGACY
440                         " legacy_protocol"
441 #endif
442 #ifdef ENABLE_JUMBOGRAMS
443                         " jumbograms"
444 #endif
445 #ifdef ENABLE_TUNEMU
446                         " tunemu"
447 #endif
448 #ifdef HAVE_MINIUPNPC
449                         " miniupnpc"
450 #endif
451 #ifdef ENABLE_UML
452                         " uml"
453 #endif
454 #ifdef ENABLE_VDE
455                         " vde"
456 #endif
457                         "\n\n"
458                         "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
459                         "See the AUTHORS file for a complete list.\n"
460                         "\n"
461                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
462                         "and you are welcome to redistribute it under certain conditions;\n"
463                         "see the file COPYING for details.\n",
464                         PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
465                 return 0;
466         }
467
468         if(show_help) {
469                 usage(false);
470                 return 0;
471         }
472
473         make_names(true);
474         atexit(cleanup);
475
476         if(chdir(confbase) == -1) {
477                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
478                 return 1;
479         }
480
481 #ifdef HAVE_WINDOWS
482
483         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
484                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
485                 return 1;
486         }
487
488 #else
489         // Check if we got an umbilical fd from the process that started us
490         char *umbstr = getenv("TINC_UMBILICAL");
491
492         if(umbstr) {
493                 int colorize = 0;
494                 sscanf(umbstr, "%d %d", &umbilical, &colorize);
495                 umbilical_colorize = colorize;
496
497                 if(fcntl(umbilical, F_GETFL) < 0) {
498                         umbilical = 0;
499                 }
500
501 #ifdef FD_CLOEXEC
502
503                 if(umbilical) {
504                         fcntl(umbilical, F_SETFD, FD_CLOEXEC);
505                 }
506
507 #endif
508         }
509
510 #endif
511
512         openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
513
514         g_argv = argv;
515
516         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
517                 do_detach = false;
518         }
519
520 #ifdef HAVE_UNSETENV
521         unsetenv("LISTEN_PID");
522 #endif
523
524         gettimeofday(&now, NULL);
525         random_init();
526         crypto_init();
527         prng_init();
528
529         if(!read_server_config(&config_tree)) {
530                 return 1;
531         }
532
533         if(debug_level == DEBUG_NOTHING) {
534                 int level = 0;
535
536                 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
537                         debug_level = level;
538                 }
539         }
540
541 #ifdef HAVE_LZO
542
543         if(lzo_init() != LZO_E_OK) {
544                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
545                 return 1;
546         }
547
548 #endif
549
550 #ifdef HAVE_WINDOWS
551         io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
552
553         if(stop_io.event == FALSE) {
554                 abort();
555         }
556
557         int result;
558
559         if(!do_detach || !init_service()) {
560                 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
561                 result = main2(argc, argv);
562         } else {
563                 result = 1;
564         }
565
566         if(WSACloseEvent(stop_io.event) == FALSE) {
567                 abort();
568         }
569
570         io_del(&stop_io);
571         return result;
572 }
573
574 int main2(int argc, char **argv) {
575         (void)argc;
576         (void)argv;
577 #endif
578         char *priority = NULL;
579
580         if(!detach()) {
581                 return 1;
582         }
583
584 #ifdef HAVE_MLOCKALL
585
586         /* Lock all pages into memory if requested.
587          * This has to be done after daemon()/fork() so it works for child.
588          * No need to do that in parent as it's very short-lived. */
589         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
590                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
591                        strerror(errno));
592                 return 1;
593         }
594
595 #endif
596
597         /* Setup sockets and open device. */
598
599         if(!setup_network()) {
600                 goto end;
601         }
602
603         /* Change process priority */
604
605         if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
606                 if(!strcasecmp(priority, "Normal")) {
607                         if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
608                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
609                                 goto end;
610                         }
611                 } else if(!strcasecmp(priority, "Low")) {
612                         if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
613                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
614                                 goto end;
615                         }
616                 } else if(!strcasecmp(priority, "High")) {
617                         if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
618                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
619                                 goto end;
620                         }
621                 } else {
622                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
623                         goto end;
624                 }
625         }
626
627         /* drop privileges */
628         if(!drop_privs()) {
629                 goto end;
630         }
631
632         /* Start main loop. It only exits when tinc is killed. */
633
634         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
635
636         if(umbilical) { // snip!
637                 if(write(umbilical, "", 1) != 1) {
638                         // Pipe full or broken, nothing we can do about it.
639                 }
640
641                 close(umbilical);
642                 umbilical = 0;
643         }
644
645         try_outgoing_connections();
646
647         status = main_loop();
648
649         /* Shutdown properly. */
650
651 end:
652         close_network_connections();
653
654         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
655
656         free(priority);
657
658         random_exit();
659
660         return status;
661 }