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