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