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