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