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