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