ff893df6ddbe8674a6eb71f226c0f71523e1e894
[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 #include <openssl/rand.h>
37 #include <openssl/rsa.h>
38 #include <openssl/pem.h>
39 #include <openssl/evp.h>
40 #include <openssl/engine.h>
41
42 #ifdef HAVE_LZO
43 #include LZO1X_H
44 #endif
45
46 #ifndef HAVE_MINGW
47 #include <pwd.h>
48 #include <grp.h>
49 #include <time.h>
50 #endif
51
52 #include <getopt.h>
53
54 #include "conf.h"
55 #include "control.h"
56 #include "crypto.h"
57 #include "device.h"
58 #include "logger.h"
59 #include "names.h"
60 #include "net.h"
61 #include "netutl.h"
62 #include "process.h"
63 #include "protocol.h"
64 #include "utils.h"
65 #include "xalloc.h"
66
67 /* If nonzero, display usage information and exit. */
68 static bool show_help = false;
69
70 /* If nonzero, print the version on standard output and exit.  */
71 static bool show_version = false;
72
73 /* If nonzero, use null ciphers and skip all key exchanges. */
74 bool bypass_security = false;
75
76 /* If nonzero, disable swapping for this process. */
77 static bool do_mlock = false;
78
79 /* If nonzero, chroot to netdir after startup. */
80 static bool do_chroot = false;
81
82 /* If !NULL, do setuid to given user after startup */
83 static const char *switchuser = NULL;
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 CRITICAL_SECTION mutex;
112 int main2(int argc, char **argv);
113 #endif
114
115 static void usage(bool status) {
116         if(status)
117                 fprintf(stderr, "Try `%s --help\' for more information.\n",
118                                 program_name);
119         else {
120                 printf("Usage: %s [option]...\n\n", program_name);
121                 printf( "  -c, --config=DIR              Read configuration options from DIR.\n"
122                                 "  -D, --no-detach               Don't fork and detach.\n"
123                                 "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
124                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
125 #ifdef HAVE_MLOCKALL
126                                 "  -L, --mlock                   Lock tinc into main memory.\n"
127 #endif
128                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
129                                 "      --pidfile=FILENAME        Write PID and control socket cookie to FILENAME.\n"
130                                 "      --bypass-security         Disables meta protocol security, for debugging.\n"
131                                 "  -o, --option[HOST.]KEY=VALUE  Set global/host configuration value.\n"
132 #ifndef HAVE_MINGW
133                                 "  -R, --chroot                  chroot to NET dir at startup.\n"
134                                 "  -U, --user=USER               setuid to given USER at startup.\n"
135 #endif
136                                 "      --help                    Display this help and exit.\n"
137                                 "      --version                 Output version information and exit.\n\n");
138                 printf("Report bugs to tinc@tinc-vpn.org.\n");
139         }
140 }
141
142 static bool parse_options(int argc, char **argv) {
143         config_t *cfg;
144         int r;
145         int option_index = 0;
146         int lineno = 0;
147
148         cmdline_conf = list_alloc((list_action_t)free_config);
149
150         while((r = getopt_long(argc, argv, "c:DLd::n:o:RU:", long_options, &option_index)) != EOF) {
151                 switch (r) {
152                         case 0:   /* long option */
153                                 break;
154
155                         case 'c': /* config file */
156                                 confbase = xstrdup(optarg);
157                                 break;
158
159                         case 'D': /* no detach */
160                                 do_detach = false;
161                                 break;
162
163                         case 'L': /* no detach */
164 #ifndef HAVE_MLOCKALL
165                                 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
166                                 return false;
167 #else
168                                 do_mlock = true;
169                                 break;
170 #endif
171
172                         case 'd': /* inc debug level */
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)
220                                         logfilename = xstrdup(optarg);
221                                 break;
222
223                         case 5:   /* open control socket here */
224                                 pidfilename = xstrdup(optarg);
225                                 break;
226
227                         case '?': /* wrong options */
228                                 usage(true);
229                                 return false;
230
231                         default:
232                                 break;
233                 }
234         }
235
236         if(!netname && (netname = getenv("NETNAME")))
237                 netname = xstrdup(netname);
238
239         /* netname "." is special: a "top-level name" */
240
241         if(netname && (!*netname || !strcmp(netname, "."))) {
242                 free(netname);
243                 netname = NULL;
244         }
245
246         if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
247                 fprintf(stderr, "Invalid character in netname!\n");
248                 return false;
249         }
250
251         return true;
252 }
253
254 static bool drop_privs(void) {
255 #ifdef HAVE_MINGW
256         return false;
257 #else
258         uid_t uid = 0;
259         if (switchuser) {
260                 struct passwd *pw = getpwnam(switchuser);
261                 if (!pw) {
262                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
263                         return false;
264                 }
265                 uid = pw->pw_uid;
266                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
267                     setgid(pw->pw_gid) != 0) {
268                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
269                                "initgroups", strerror(errno));
270                         return false;
271                 }
272 #ifndef __ANDROID__
273 // Not supported in android NDK
274                 endgrent();
275                 endpwent();
276 #endif
277         }
278         if (do_chroot) {
279                 tzset();        /* for proper timestamps in logs */
280                 if (chroot(confbase) != 0 || chdir("/") != 0) {
281                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
282                                "chroot", strerror(errno));
283                         return false;
284                 }
285                 free(confbase);
286                 confbase = xstrdup("");
287         }
288         if (switchuser)
289                 if (setuid(uid) != 0) {
290                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
291                                "setuid", strerror(errno));
292                         return false;
293                 }
294 #endif
295         return true;
296 }
297
298 #ifdef HAVE_MINGW
299 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
300 #else
301 # define NORMAL_PRIORITY_CLASS 0
302 # define BELOW_NORMAL_PRIORITY_CLASS 10
303 # define HIGH_PRIORITY_CLASS -10
304 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
305 #endif
306
307 int main(int argc, char **argv) {
308         program_name = argv[0];
309
310         if(!parse_options(argc, argv))
311                 return 1;
312
313         make_names();
314
315         if(show_version) {
316                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
317                            VERSION, __DATE__, __TIME__, PROT_MAJOR, PROT_MINOR);
318                 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
319                                 "See the AUTHORS file for a complete list.\n\n"
320                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
321                                 "and you are welcome to redistribute it under certain conditions;\n"
322                                 "see the file COPYING for details.\n");
323
324                 return 0;
325         }
326
327         if(show_help) {
328                 usage(false);
329                 return 0;
330         }
331
332 #ifdef HAVE_MINGW
333         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
334                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
335                 return 1;
336         }
337 #endif
338
339         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
340
341         g_argv = argv;
342
343         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
344                 do_detach = false;
345 #ifdef HAVE_UNSETENV
346         unsetenv("LISTEN_PID");
347 #endif
348
349         init_configuration(&config_tree);
350
351         /* Slllluuuuuuurrrrp! */
352
353         srand(time(NULL));
354         crypto_init();
355
356         if(!read_server_config())
357                 return 1;
358
359 #ifdef HAVE_LZO
360         if(lzo_init() != LZO_E_OK) {
361                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
362                 return 1;
363         }
364 #endif
365
366 #ifdef HAVE_MINGW
367         if(!do_detach || !init_service())
368                 return main2(argc, argv);
369         else
370                 return 1;
371 }
372
373 int main2(int argc, char **argv) {
374         InitializeCriticalSection(&mutex);
375         EnterCriticalSection(&mutex);
376 #endif
377         char *priority = NULL;
378
379         if(!detach())
380                 return 1;
381
382 #ifdef HAVE_MLOCKALL
383         /* Lock all pages into memory if requested.
384          * This has to be done after daemon()/fork() so it works for child.
385          * No need to do that in parent as it's very short-lived. */
386         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
387                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
388                    strerror(errno));
389                 return 1;
390         }
391 #endif
392
393         /* Setup sockets and open device. */
394
395         if(!setup_network())
396                 goto end_nonet;
397
398         if(!init_control())
399                 goto end_nonet;
400
401         /* Initiate all outgoing connections. */
402
403         try_outgoing_connections();
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         status = main_loop();
436
437         /* Shutdown properly. */
438
439         if(debug_level >= DEBUG_CONNECTIONS)
440                 devops.dump_stats();
441
442         close_network_connections();
443
444 end:
445         exit_control();
446
447 end_nonet:
448         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
449
450         free(priority);
451
452         crypto_exit();
453
454         exit_configuration(&config_tree);
455         free(cmdline_conf);
456         free_names();
457
458         return status;
459 }