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