5bfeeabb364cbe68b32b919d86520a0ff18c2088
[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                 static const char *message =
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
157                 printf(message, program_name);
158         }
159 }
160
161 static bool parse_options(int argc, char **argv) {
162         config_t *cfg;
163         int r;
164         int option_index = 0;
165         int lineno = 0;
166
167         while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
168                 switch((option_t) r) {
169                 case OPT_LONG_OPTION:
170                         break;
171
172                 case OPT_BAD_OPTION:
173                         usage(true);
174                         goto exit_fail;
175
176                 case OPT_CONFIG_FILE:
177                         free(confbase);
178                         confbase = xstrdup(optarg);
179                         break;
180
181                 case OPT_NO_DETACH:
182                         do_detach = false;
183                         break;
184
185                 case OPT_MLOCK: /* lock tincd into RAM */
186 #ifndef HAVE_MLOCKALL
187                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
188                         goto exit_fail;
189 #else
190                         do_mlock = true;
191                         break;
192 #endif
193
194                 case OPT_DEBUG: /* increase debug level */
195                         if(!optarg && optind < argc && *argv[optind] != '-') {
196                                 optarg = argv[optind++];
197                         }
198
199                         if(optarg) {
200                                 debug_level = atoi(optarg);
201                         } else {
202                                 debug_level++;
203                         }
204
205                         break;
206
207                 case OPT_NETNAME:
208                         free(netname);
209                         netname = xstrdup(optarg);
210                         break;
211
212                 case OPT_SYSLOG:
213                         use_logfile = false;
214                         use_syslog = true;
215                         break;
216
217                 case OPT_OPTION:
218                         cfg = parse_config_line(optarg, NULL, ++lineno);
219
220                         if(!cfg) {
221                                 goto exit_fail;
222                         }
223
224                         list_insert_tail(&cmdline_conf, cfg);
225                         break;
226
227 #ifdef HAVE_WINDOWS
228
229                 case OPT_CHANGE_USER:
230                 case OPT_CHROOT:
231                         logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
232                         goto exit_fail;
233 #else
234
235                 case OPT_CHROOT:
236                         do_chroot = true;
237                         break;
238
239                 case OPT_CHANGE_USER:
240                         switchuser = optarg;
241                         break;
242 #endif
243
244                 case OPT_HELP:
245                         show_help = true;
246                         break;
247
248                 case OPT_VERSION:
249                         show_version = true;
250                         break;
251
252                 case OPT_NO_SECURITY:
253                         bypass_security = true;
254                         break;
255
256                 case OPT_LOGFILE:
257                         use_syslog = false;
258                         use_logfile = true;
259
260                         if(!optarg && optind < argc && *argv[optind] != '-') {
261                                 optarg = argv[optind++];
262                         }
263
264                         if(optarg) {
265                                 free(logfilename);
266                                 logfilename = xstrdup(optarg);
267                         }
268
269                         break;
270
271                 case OPT_PIDFILE:
272                         free(pidfilename);
273                         pidfilename = xstrdup(optarg);
274                         break;
275
276                 default:
277                         break;
278                 }
279         }
280
281         if(optind < argc) {
282                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
283                 usage(true);
284                 goto exit_fail;
285         }
286
287         if(!netname && (netname = getenv("NETNAME"))) {
288                 netname = xstrdup(netname);
289         }
290
291         /* netname "." is special: a "top-level name" */
292
293         if(netname && (!*netname || !strcmp(netname, "."))) {
294                 free(netname);
295                 netname = NULL;
296         }
297
298         if(netname && !check_netname(netname, false)) {
299                 fprintf(stderr, "Invalid character in netname!\n");
300                 goto exit_fail;
301         }
302
303         if(netname && !check_netname(netname, true)) {
304                 fprintf(stderr, "Warning: unsafe character in netname!\n");
305         }
306
307         return true;
308
309 exit_fail:
310         free_names();
311         list_empty_list(&cmdline_conf);
312         return false;
313 }
314
315 static bool drop_privs(void) {
316 #ifndef HAVE_WINDOWS
317         uid_t uid = 0;
318
319         if(switchuser) {
320                 struct passwd *pw = getpwnam(switchuser);
321
322                 if(!pw) {
323                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
324                         return false;
325                 }
326
327                 uid = pw->pw_uid;
328
329                 // The second parameter to initgroups on macOS requires int,
330                 // but __gid_t is unsigned int. There's not much we can do here.
331                 if(initgroups(switchuser, pw->pw_gid) != 0 || // NOLINT(bugprone-narrowing-conversions)
332                                 setgid(pw->pw_gid) != 0) {
333                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
334                                "initgroups", strerror(errno));
335                         return false;
336                 }
337
338 #ifndef __ANDROID__
339 // Not supported in android NDK
340                 endgrent();
341                 endpwent();
342 #endif
343         }
344
345         if(do_chroot) {
346                 tzset();        /* for proper timestamps in logs */
347
348                 if(chroot(confbase) != 0 || chdir("/") != 0) {
349                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
350                                "chroot", strerror(errno));
351                         return false;
352                 }
353
354                 free(confbase);
355                 confbase = xstrdup("");
356         }
357
358         if(switchuser)
359                 if(setuid(uid) != 0) {
360                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
361                                "setuid", strerror(errno));
362                         return false;
363                 }
364
365 #endif
366         return true;
367 }
368
369 #ifdef HAVE_WINDOWS
370 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
371
372 static void stop_handler(void *data, int flags) {
373         (void)data;
374         (void)flags;
375
376         event_exit();
377 }
378
379 static BOOL WINAPI console_ctrl_handler(DWORD type) {
380         (void)type;
381
382         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
383
384         if(WSASetEvent(stop_io.event) == FALSE) {
385                 abort();
386         }
387
388         return TRUE;
389 }
390 #else
391 # define NORMAL_PRIORITY_CLASS 0
392 # define BELOW_NORMAL_PRIORITY_CLASS 10
393 # define HIGH_PRIORITY_CLASS -10
394 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
395 #endif
396
397 static void cleanup(void) {
398         splay_empty_tree(&config_tree);
399         list_empty_list(&cmdline_conf);
400         free_names();
401 }
402
403 int main(int argc, char **argv) {
404         program_name = argv[0];
405
406         if(!parse_options(argc, argv)) {
407                 return 1;
408         }
409
410         if(show_version) {
411                 static const char *message =
412                         "%s version %s (built %s %s, protocol %d.%d)\n"
413                         "Features:"
414 #ifdef HAVE_OPENSSL
415                         " openssl"
416 #endif
417 #ifdef HAVE_LIBGCRYPT
418                         " libgcrypt"
419 #endif
420 #ifdef HAVE_LZO
421                         " comp_lzo"
422 #endif
423 #ifdef HAVE_ZLIB
424                         " comp_zlib"
425 #endif
426 #ifdef HAVE_LZ4
427                         " comp_lz4"
428 #endif
429 #ifndef DISABLE_LEGACY
430                         " legacy_protocol"
431 #endif
432 #ifdef ENABLE_JUMBOGRAMS
433                         " jumbograms"
434 #endif
435 #ifdef ENABLE_TUNEMU
436                         " tunemu"
437 #endif
438 #ifdef HAVE_MINIUPNPC
439                         " miniupnpc"
440 #endif
441 #ifdef ENABLE_UML
442                         " uml"
443 #endif
444 #ifdef ENABLE_VDE
445                         " vde"
446 #endif
447                         "\n\n"
448                         "Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
449                         "See the AUTHORS file for a complete list.\n"
450                         "\n"
451                         "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
452                         "and you are welcome to redistribute it under certain conditions;\n"
453                         "see the file COPYING for details.\n";
454
455                 printf(message, PACKAGE, BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
456                 return 0;
457         }
458
459         if(show_help) {
460                 usage(false);
461                 return 0;
462         }
463
464         make_names(true);
465         atexit(cleanup);
466
467         if(chdir(confbase) == -1) {
468                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not change to configuration directory: %s", strerror(errno));
469                 return 1;
470         }
471
472 #ifdef HAVE_WINDOWS
473
474         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
475                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
476                 return 1;
477         }
478
479 #else
480         // Check if we got an umbilical fd from the process that started us
481         char *umbstr = getenv("TINC_UMBILICAL");
482
483         if(umbstr) {
484                 int colorize = 0;
485                 sscanf(umbstr, "%d %d", &umbilical, &colorize);
486                 umbilical_colorize = colorize;
487
488                 if(fcntl(umbilical, F_GETFL) < 0) {
489                         umbilical = 0;
490                 }
491
492 #ifdef FD_CLOEXEC
493
494                 if(umbilical) {
495                         fcntl(umbilical, F_SETFD, FD_CLOEXEC);
496                 }
497
498 #endif
499         }
500
501 #endif
502
503         openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
504
505         g_argv = argv;
506
507         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
508                 do_detach = false;
509         }
510
511 #ifdef HAVE_UNSETENV
512         unsetenv("LISTEN_PID");
513 #endif
514
515         gettimeofday(&now, NULL);
516         random_init();
517         crypto_init();
518         prng_init();
519
520         if(!read_server_config(&config_tree)) {
521                 return 1;
522         }
523
524         if(debug_level == DEBUG_NOTHING) {
525                 int level = 0;
526
527                 if(get_config_int(lookup_config(&config_tree, "LogLevel"), &level)) {
528                         debug_level = level;
529                 }
530         }
531
532 #ifdef HAVE_LZO
533
534         if(lzo_init() != LZO_E_OK) {
535                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
536                 return 1;
537         }
538
539 #endif
540
541 #ifdef HAVE_WINDOWS
542         io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
543
544         if(stop_io.event == FALSE) {
545                 abort();
546         }
547
548         int result;
549
550         if(!do_detach || !init_service()) {
551                 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
552                 result = main2(argc, argv);
553         } else {
554                 result = 1;
555         }
556
557         if(WSACloseEvent(stop_io.event) == FALSE) {
558                 abort();
559         }
560
561         io_del(&stop_io);
562         return result;
563 }
564
565 int main2(int argc, char **argv) {
566         (void)argc;
567         (void)argv;
568 #endif
569         char *priority = NULL;
570
571         if(!detach()) {
572                 return 1;
573         }
574
575 #ifdef HAVE_MLOCKALL
576
577         /* Lock all pages into memory if requested.
578          * This has to be done after daemon()/fork() so it works for child.
579          * No need to do that in parent as it's very short-lived. */
580         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
581                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
582                        strerror(errno));
583                 return 1;
584         }
585
586 #endif
587
588         /* Setup sockets and open device. */
589
590         if(!setup_network()) {
591                 goto end;
592         }
593
594         /* Change process priority */
595
596         if(get_config_string(lookup_config(&config_tree, "ProcessPriority"), &priority)) {
597                 if(!strcasecmp(priority, "Normal")) {
598                         if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
599                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
600                                 goto end;
601                         }
602                 } else if(!strcasecmp(priority, "Low")) {
603                         if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
604                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
605                                 goto end;
606                         }
607                 } else if(!strcasecmp(priority, "High")) {
608                         if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
609                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
610                                 goto end;
611                         }
612                 } else {
613                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
614                         goto end;
615                 }
616         }
617
618         /* drop privileges */
619         if(!drop_privs()) {
620                 goto end;
621         }
622
623         /* Start main loop. It only exits when tinc is killed. */
624
625         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
626
627         if(umbilical) { // snip!
628                 if(write(umbilical, "", 1) != 1) {
629                         // Pipe full or broken, nothing we can do about it.
630                 }
631
632                 close(umbilical);
633                 umbilical = 0;
634         }
635
636         try_outgoing_connections();
637
638         status = main_loop();
639
640         /* Shutdown properly. */
641
642 end:
643         close_network_connections();
644
645         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
646
647         free(priority);
648
649         random_exit();
650
651         return status;
652 }