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