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