35a84be1230e9b74acbb4bd4f8d6ce99ec4622ca
[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                 if(initgroups(switchuser, pw->pw_gid) != 0 ||
317                                 setgid(pw->pw_gid) != 0) {
318                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
319                                "initgroups", strerror(errno));
320                         return false;
321                 }
322
323 #ifndef __ANDROID__
324 // Not supported in android NDK
325                 endgrent();
326                 endpwent();
327 #endif
328         }
329
330         if(do_chroot) {
331                 tzset();        /* for proper timestamps in logs */
332
333                 if(chroot(confbase) != 0 || chdir("/") != 0) {
334                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
335                                "chroot", strerror(errno));
336                         return false;
337                 }
338
339                 free(confbase);
340                 confbase = xstrdup("");
341         }
342
343         if(switchuser)
344                 if(setuid(uid) != 0) {
345                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
346                                "setuid", strerror(errno));
347                         return false;
348                 }
349
350 #endif
351         return true;
352 }
353
354 #ifdef HAVE_MINGW
355 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
356
357 static void stop_handler(void *data, int flags) {
358         (void)data;
359         (void)flags;
360
361         event_exit();
362 }
363
364 static BOOL WINAPI console_ctrl_handler(DWORD type) {
365         (void)type;
366
367         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
368
369         if(WSASetEvent(stop_io.event) == FALSE) {
370                 abort();
371         }
372
373         return TRUE;
374 }
375 #else
376 # define NORMAL_PRIORITY_CLASS 0
377 # define BELOW_NORMAL_PRIORITY_CLASS 10
378 # define HIGH_PRIORITY_CLASS -10
379 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
380 #endif
381
382 static void cleanup() {
383         if(config_tree) {
384                 exit_configuration(&config_tree);
385         }
386
387         list_delete_list(cmdline_conf);
388         free_names();
389 }
390
391 int main(int argc, char **argv) {
392         program_name = argv[0];
393
394         if(!parse_options(argc, argv)) {
395                 return 1;
396         }
397
398         if(show_version) {
399                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
400                        BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
401                 printf("Features:"
402 #ifdef HAVE_OPENSSL
403                        " openssl"
404 #endif
405 #ifdef HAVE_LIBGCRYPT
406                        " libgcrypt"
407 #endif
408 #ifdef HAVE_LZO
409                        " comp_lzo"
410 #endif
411 #ifdef HAVE_ZLIB
412                        " comp_zlib"
413 #endif
414 #ifdef HAVE_LZ4
415                        " comp_lz4"
416 #endif
417 #ifndef DISABLE_LEGACY
418                        " legacy_protocol"
419 #endif
420 #ifdef ENABLE_JUMBOGRAMS
421                        " jumbograms"
422 #endif
423 #ifdef ENABLE_TUNEMU
424                        " tunemu"
425 #endif
426 #ifdef HAVE_MINIUPNPC
427                        " miniupnpc"
428 #endif
429 #ifdef ENABLE_UML
430                        " uml"
431 #endif
432 #ifdef ENABLE_VDE
433                        " vde"
434 #endif
435                        "\n\n");
436                 printf("Copyright (C) 1998-2021 Ivo Timmermans, Guus Sliepen and others.\n"
437                        "See the AUTHORS file for a complete list.\n\n"
438                        "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
439                        "and you are welcome to redistribute it under certain conditions;\n"
440                        "see the file COPYING for details.\n");
441
442                 return 0;
443         }
444
445         if(show_help) {
446                 usage(false);
447                 return 0;
448         }
449
450         make_names(true);
451         atexit(cleanup);
452
453         chdir(confbase);
454
455 #ifdef HAVE_MINGW
456
457         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
458                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
459                 return 1;
460         }
461
462 #else
463         // Check if we got an umbilical fd from the process that started us
464         char *umbstr = getenv("TINC_UMBILICAL");
465
466         if(umbstr) {
467                 umbilical = atoi(umbstr);
468
469                 if(fcntl(umbilical, F_GETFL) < 0) {
470                         umbilical = 0;
471                 }
472
473 #ifdef FD_CLOEXEC
474
475                 if(umbilical) {
476                         fcntl(umbilical, F_SETFD, FD_CLOEXEC);
477                 }
478
479 #endif
480         }
481
482 #endif
483
484         openlogger("tinc", use_logfile ? LOGMODE_FILE : LOGMODE_STDERR);
485
486         g_argv = argv;
487
488         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
489                 do_detach = false;
490         }
491
492 #ifdef HAVE_UNSETENV
493         unsetenv("LISTEN_PID");
494 #endif
495
496         init_configuration(&config_tree);
497
498         /* Slllluuuuuuurrrrp! */
499
500         gettimeofday(&now, NULL);
501         srand(now.tv_sec + now.tv_usec);
502         crypto_init();
503
504         if(!read_server_config(config_tree)) {
505                 return 1;
506         }
507
508         if(!debug_level) {
509                 get_config_int(lookup_config(config_tree, "LogLevel"), &debug_level);
510         }
511
512 #ifdef HAVE_LZO
513
514         if(lzo_init() != LZO_E_OK) {
515                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
516                 return 1;
517         }
518
519 #endif
520
521 #ifdef HAVE_MINGW
522         io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
523
524         if(stop_io.event == FALSE) {
525                 abort();
526         }
527
528         int result;
529
530         if(!do_detach || !init_service()) {
531                 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
532                 result = main2(argc, argv);
533         } else {
534                 result = 1;
535         }
536
537         if(WSACloseEvent(stop_io.event) == FALSE) {
538                 abort();
539         }
540
541         io_del(&stop_io);
542         return result;
543 }
544
545 int main2(int argc, char **argv) {
546         (void)argc;
547         (void)argv;
548 #endif
549         char *priority = NULL;
550
551         if(!detach()) {
552                 return 1;
553         }
554
555 #ifdef HAVE_MLOCKALL
556
557         /* Lock all pages into memory if requested.
558          * This has to be done after daemon()/fork() so it works for child.
559          * No need to do that in parent as it's very short-lived. */
560         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
561                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
562                        strerror(errno));
563                 return 1;
564         }
565
566 #endif
567
568         /* Setup sockets and open device. */
569
570         if(!setup_network()) {
571                 goto end;
572         }
573
574         /* Change process priority */
575
576         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
577                 if(!strcasecmp(priority, "Normal")) {
578                         if(setpriority(NORMAL_PRIORITY_CLASS) != 0) {
579                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
580                                 goto end;
581                         }
582                 } else if(!strcasecmp(priority, "Low")) {
583                         if(setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
584                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
585                                 goto end;
586                         }
587                 } else if(!strcasecmp(priority, "High")) {
588                         if(setpriority(HIGH_PRIORITY_CLASS) != 0) {
589                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
590                                 goto end;
591                         }
592                 } else {
593                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
594                         goto end;
595                 }
596         }
597
598         /* drop privileges */
599         if(!drop_privs()) {
600                 goto end;
601         }
602
603         /* Start main loop. It only exits when tinc is killed. */
604
605         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
606
607         if(umbilical) { // snip!
608                 write(umbilical, "", 1);
609                 close(umbilical);
610                 umbilical = 0;
611         }
612
613         try_outgoing_connections();
614
615         status = main_loop();
616
617         /* Shutdown properly. */
618
619 end:
620         close_network_connections();
621
622         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
623
624         free(priority);
625
626         crypto_exit();
627
628         return status;
629 }