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