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