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