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