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