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