]> git.meshlink.io Git - meshlink/blob - src/tincd.c
Merge branch 'master' into 1.1
[meshlink] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2009 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id$
21 */
22
23 #include "system.h"
24
25 /* Darwin (MacOS/X) needs the following definition... */
26 #ifndef _P1003_1B_VISIBLE
27 #define _P1003_1B_VISIBLE
28 #endif
29
30 #ifdef HAVE_SYS_MMAN_H
31 #include <sys/mman.h>
32 #endif
33
34 #include LZO1X_H
35
36 #ifndef HAVE_MINGW
37 #include <pwd.h>
38 #include <grp.h>
39 #include <time.h>
40 #endif
41
42 #include <getopt.h>
43
44 #include "conf.h"
45 #include "control.h"
46 #include "crypto.h"
47 #include "device.h"
48 #include "logger.h"
49 #include "net.h"
50 #include "netutl.h"
51 #include "process.h"
52 #include "protocol.h"
53 #include "utils.h"
54 #include "xalloc.h"
55
56 /* The name this program was run with. */
57 char *program_name = NULL;
58
59 /* If nonzero, display usage information and exit. */
60 bool show_help = false;
61
62 /* If nonzero, print the version on standard output and exit.  */
63 bool show_version = false;
64
65 /* If nonzero, use null ciphers and skip all key exchanges. */
66 bool bypass_security = false;
67
68 /* If nonzero, disable swapping for this process. */
69 bool do_mlock = false;
70
71 /* If nonzero, chroot to netdir after startup. */
72 static bool do_chroot = false;
73
74 /* If !NULL, do setuid to given user after startup */
75 static const char *switchuser = NULL;
76
77 /* If nonzero, write log entries to a separate file. */
78 bool use_logfile = false;
79
80 char *identname = NULL;                         /* program name for syslog */
81 char *controlsocketname = NULL;                 /* control socket location */
82 char *logfilename = NULL;                       /* log file location */
83 char **g_argv;                                  /* a copy of the cmdline arguments */
84
85 static int status;
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         {"controlsocket", required_argument, NULL, 5},
100         {NULL, 0, NULL, 0}
101 };
102
103 #ifdef HAVE_MINGW
104 static struct WSAData wsa_state;
105 CRITICAL_SECTION mutex;
106 #endif
107
108 static void usage(bool status)
109 {
110         if(status)
111                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
112                                 program_name);
113         else {
114                 printf(_("Usage: %s [option]...\n\n"), program_name);
115                 printf(_(       "  -c, --config=DIR              Read configuration options from DIR.\n"
116                                 "  -D, --no-detach               Don't fork and detach.\n"
117                                 "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
118                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
119                                 "  -L, --mlock                   Lock tinc into main memory.\n"
120                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
121                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
122                                 "      --bypass-security         Disables meta protocol security, for debugging.\n"
123                                 "  -R, --chroot                  chroot to NET dir at startup.\n"
124                                 "  -U, --user=USER               setuid to given USER at startup.\n"                            "      --help                    Display this help and exit.\n"
125                                 "      --version                 Output version information and exit.\n\n"));
126                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
127         }
128 }
129
130 static bool parse_options(int argc, char **argv)
131 {
132         int r;
133         int option_index = 0;
134
135         while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
136                 switch (r) {
137                         case 0:                         /* long option */
138                                 break;
139
140                         case 'c':                               /* config file */
141                                 confbase = xstrdup(optarg);
142                                 break;
143
144                         case 'D':                               /* no detach */
145                                 do_detach = false;
146                                 break;
147
148                         case 'L':                               /* no detach */
149 #ifndef HAVE_MLOCKALL
150                                 logger(LOG_ERR, _("%s not supported on this platform"), "mlockall()");
151                                 return false;
152 #else
153                                 do_mlock = true;
154                                 break;
155 #endif
156
157                         case 'd':                               /* inc debug level */
158                                 if(optarg)
159                                         debug_level = atoi(optarg);
160                                 else
161                                         debug_level++;
162                                 break;
163
164                         case 'n':                               /* net name given */
165                                 netname = xstrdup(optarg);
166                                 break;
167
168                         case 'R':                               /* chroot to NETNAME dir */
169                                 do_chroot = true;
170                                 break;
171
172                         case 'U':                               /* setuid to USER */
173                                 switchuser = optarg;
174                                 break;
175
176                         case 1:                                 /* show help */
177                                 show_help = true;
178                                 break;
179
180                         case 2:                                 /* show version */
181                                 show_version = true;
182                                 break;
183
184                         case 3:                                 /* bypass security */
185                                 bypass_security = true;
186                                 break;
187
188                         case 4:                                 /* write log entries to a file */
189                                 use_logfile = true;
190                                 if(optarg)
191                                         logfilename = xstrdup(optarg);
192                                 break;
193
194                         case 5:                                 /* open control socket here */
195                                 controlsocketname = xstrdup(optarg);
196                                 break;
197
198                         case '?':
199                                 usage(true);
200                                 return false;
201
202                         default:
203                                 break;
204                 }
205         }
206
207         return true;
208 }
209
210 /*
211   Set all files and paths according to netname
212 */
213 static void make_names(void)
214 {
215 #ifdef HAVE_MINGW
216         HKEY key;
217         char installdir[1024] = "";
218         long len = sizeof installdir;
219 #endif
220
221         if(netname)
222                 xasprintf(&identname, "tinc.%s", netname);
223         else
224                 identname = xstrdup("tinc");
225
226 #ifdef HAVE_MINGW
227         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
228                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
229                         if(!logfilename)
230                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
231                         if(!confbase) {
232                                 if(netname)
233                                         xasprintf(&confbase, "%s/%s", installdir, netname);
234                                 else
235                                         xasprintf(&confbase, "%s", installdir);
236                         }
237                 }
238                 RegCloseKey(key);
239                 if(*installdir)
240                         return;
241         }
242 #endif
243
244         if(!controlsocketname)
245                 xasprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
246
247         if(!logfilename)
248                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
249
250         if(netname) {
251                 if(!confbase)
252                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
253                 else
254                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
255         } else {
256                 if(!confbase)
257                         xasprintf(&confbase, CONFDIR "/tinc");
258         }
259 }
260
261 static void free_names() {
262         if (identname) free(identname);
263         if (netname) free(netname);
264         if (controlsocketname) free(controlsocketname);
265         if (logfilename) free(logfilename);
266         if (confbase) free(confbase);
267 }
268
269 static bool drop_privs() {
270 #ifdef HAVE_MINGW
271         if (switchuser) {
272                 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
273                 return false;
274         }
275         if (do_chroot) {
276                 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
277                 return false;
278         }
279 #else
280         uid_t uid = 0;
281         if (switchuser) {
282                 struct passwd *pw = getpwnam(switchuser);
283                 if (!pw) {
284                         logger(LOG_ERR, _("unknown user `%s'"), switchuser);
285                         return false;
286                 }
287                 uid = pw->pw_uid;
288                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
289                     setgid(pw->pw_gid) != 0) {
290                         logger(LOG_ERR, _("System call `%s' failed: %s"),
291                                "initgroups", strerror(errno));
292                         return false;
293                 }
294                 endgrent();
295                 endpwent();
296         }
297         if (do_chroot) {
298                 tzset();        /* for proper timestamps in logs */
299                 if (chroot(confbase) != 0 || chdir("/") != 0) {
300                         logger(LOG_ERR, _("System call `%s' failed: %s"),
301                                "chroot", strerror(errno));
302                         return false;
303                 }
304                 free(confbase);
305                 confbase = xstrdup("");
306         }
307         if (switchuser)
308                 if (setuid(uid) != 0) {
309                         logger(LOG_ERR, _("System call `%s' failed: %s"),
310                                "setuid", strerror(errno));
311                         return false;
312                 }
313 #endif
314         return true;
315 }
316
317 #ifdef HAVE_MINGW
318 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level)
319 #else
320 # define NORMAL_PRIORITY_CLASS 0
321 # define BELOW_NORMAL_PRIORITY_CLASS 10
322 # define HIGH_PRIORITY_CLASS -10
323 # define setpriority(level) nice(level)
324 #endif
325
326 int main(int argc, char **argv)
327 {
328         program_name = argv[0];
329
330         setlocale(LC_ALL, "");
331         bindtextdomain(PACKAGE, LOCALEDIR);
332         textdomain(PACKAGE);
333
334         if(!parse_options(argc, argv))
335                 return 1;
336         
337         make_names();
338
339         if(show_version) {
340                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
341                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
342                 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
343                                 "See the AUTHORS file for a complete list.\n\n"
344                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
345                                 "and you are welcome to redistribute it under certain conditions;\n"
346                                 "see the file COPYING for details.\n"));
347
348                 return 0;
349         }
350
351         if(show_help) {
352                 usage(false);
353                 return 0;
354         }
355
356         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
357
358         if(!event_init()) {
359                 logger(LOG_ERR, _("Error initializing libevent!"));
360                 return 1;
361         }
362
363         if(!init_control())
364                 return 1;
365
366         g_argv = argv;
367
368         init_configuration(&config_tree);
369
370         /* Slllluuuuuuurrrrp! */
371
372         srand(time(NULL));
373         crypto_init();
374
375         if(!read_server_config())
376                 return 1;
377
378         if(lzo_init() != LZO_E_OK) {
379                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
380                 return 1;
381         }
382
383 #ifdef HAVE_MINGW
384         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
385                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
386                 return 1;
387         }
388
389         if(!do_detach || !init_service())
390                 return main2(argc, argv);
391         else
392                 return 1;
393 }
394
395 int main2(int argc, char **argv)
396 {
397         InitializeCriticalSection(&mutex);
398         EnterCriticalSection(&mutex);
399 #endif
400
401         if(!detach())
402                 return 1;
403
404 #ifdef HAVE_MLOCKALL
405         /* Lock all pages into memory if requested.
406          * This has to be done after daemon()/fork() so it works for child.
407          * No need to do that in parent as it's very short-lived. */
408         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
409                 logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
410                    strerror(errno));
411                 return 1;
412         }
413 #endif
414
415         /* Setup sockets and open device. */
416
417         if(!setup_network())
418                 goto end;
419
420         /* Initiate all outgoing connections. */
421
422         try_outgoing_connections();
423
424         /* Change process priority */
425
426         char *priority = 0;
427
428         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
429                 if(!strcasecmp(priority, "Normal"))
430                         setpriority(NORMAL_PRIORITY_CLASS);
431                 else if(!strcasecmp(priority, "Low"))
432                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
433                 else if(!strcasecmp(priority, "High"))
434                         setpriority(HIGH_PRIORITY_CLASS);
435                 else {
436                         logger(LOG_ERR, _("Invalid priority `%s`!"), priority);
437                         goto end;
438                 }
439         }
440
441         /* drop privileges */
442         if (!drop_privs())
443                 goto end;
444
445         /* Start main loop. It only exits when tinc is killed. */
446
447         status = main_loop();
448
449         /* Shutdown properly. */
450
451         ifdebug(CONNECTIONS)
452                 dump_device_stats();
453
454         close_network_connections();
455
456 end:
457         logger(LOG_NOTICE, _("Terminating"));
458
459 #ifndef HAVE_MINGW
460         exit_control();
461 #endif
462
463         crypto_exit();
464
465         exit_configuration(&config_tree);
466         free_names();
467
468         return status;
469 }