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