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