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