]> git.meshlink.io Git - meshlink/blob - src/tincd.c
Fix pointer arithmetic when creating and verifying message authentication codes.
[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 #endif
106
107 static void usage(bool status)
108 {
109         if(status)
110                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
111                                 program_name);
112         else {
113                 printf(_("Usage: %s [option]...\n\n"), program_name);
114                 printf(_(       "  -c, --config=DIR              Read configuration options from DIR.\n"
115                                 "  -D, --no-detach               Don't fork and detach.\n"
116                                 "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
117                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
118                                 "  -L, --mlock                   Lock tinc into main memory.\n"
119                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
120                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
121                                 "      --bypass-security         Disables meta protocol security, for debugging.\n"
122                                 "  -R, --chroot                  chroot to NET dir at startup.\n"
123                                 "  -U, --user=USER               setuid to given USER at startup.\n"                            "      --help                    Display this help and exit.\n"
124                                 "      --version                 Output version information and exit.\n\n"));
125                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
126         }
127 }
128
129 static bool parse_options(int argc, char **argv)
130 {
131         int r;
132         int option_index = 0;
133
134         while((r = getopt_long(argc, argv, "c:DLd::n:RU:", long_options, &option_index)) != EOF) {
135                 switch (r) {
136                         case 0:                         /* long option */
137                                 break;
138
139                         case 'c':                               /* config file */
140                                 confbase = xstrdup(optarg);
141                                 break;
142
143                         case 'D':                               /* no detach */
144                                 do_detach = false;
145                                 break;
146
147                         case 'L':                               /* no detach */
148 #ifndef HAVE_MLOCKALL
149                                 logger(LOG_ERR, _("%s not supported on this platform"), "mlockall()");
150                                 return false;
151 #else
152                                 do_mlock = true;
153                                 break;
154 #endif
155
156                         case 'd':                               /* inc debug level */
157                                 if(optarg)
158                                         debug_level = atoi(optarg);
159                                 else
160                                         debug_level++;
161                                 break;
162
163                         case 'n':                               /* net name given */
164                                 netname = xstrdup(optarg);
165                                 break;
166
167                         case 'R':                               /* chroot to NETNAME dir */
168                                 do_chroot = true;
169                                 break;
170
171                         case 'U':                               /* setuid to USER */
172                                 switchuser = optarg;
173                                 break;
174
175                         case 1:                                 /* show help */
176                                 show_help = true;
177                                 break;
178
179                         case 2:                                 /* show version */
180                                 show_version = true;
181                                 break;
182
183                         case 3:                                 /* bypass security */
184                                 bypass_security = true;
185                                 break;
186
187                         case 4:                                 /* write log entries to a file */
188                                 use_logfile = true;
189                                 if(optarg)
190                                         logfilename = xstrdup(optarg);
191                                 break;
192
193                         case 5:                                 /* open control socket here */
194                                 controlsocketname = xstrdup(optarg);
195                                 break;
196
197                         case '?':
198                                 usage(true);
199                                 return false;
200
201                         default:
202                                 break;
203                 }
204         }
205
206         return true;
207 }
208
209 /*
210   Set all files and paths according to netname
211 */
212 static void make_names(void)
213 {
214 #ifdef HAVE_MINGW
215         HKEY key;
216         char installdir[1024] = "";
217         long len = sizeof installdir;
218 #endif
219
220         if(netname)
221                 asprintf(&identname, "tinc.%s", netname);
222         else
223                 identname = xstrdup("tinc");
224
225 #ifdef HAVE_MINGW
226         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
227                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
228                         if(!logfilename)
229                                 asprintf(&logfilename, "%s/log/%s.log", identname);
230                         if(!confbase) {
231                                 if(netname)
232                                         asprintf(&confbase, "%s/%s", installdir, netname);
233                                 else
234                                         asprintf(&confbase, "%s", installdir);
235                         }
236                 }
237                 RegCloseKey(key);
238                 if(*installdir)
239                         return;
240         }
241 #endif
242
243         if(!controlsocketname)
244                 asprintf(&controlsocketname, "%s/run/%s.control/socket", LOCALSTATEDIR, identname);
245
246         if(!logfilename)
247                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
248
249         if(netname) {
250                 if(!confbase)
251                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
252                 else
253                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
254         } else {
255                 if(!confbase)
256                         asprintf(&confbase, CONFDIR "/tinc");
257         }
258 }
259
260 static void free_names() {
261         if (identname) free(identname);
262         if (netname) free(netname);
263         if (controlsocketname) free(controlsocketname);
264         if (logfilename) free(logfilename);
265         if (confbase) free(confbase);
266 }
267
268 static bool drop_privs() {
269 #ifdef HAVE_MINGW
270         if (switchuser) {
271                 logger(LOG_ERR, _("%s not supported on this platform"), "-U");
272                 return false;
273         }
274         if (do_chroot) {
275                 logger(LOG_ERR, _("%s not supported on this platform"), "-R");
276                 return false;
277         }
278 #else
279         uid_t uid = 0;
280         if (switchuser) {
281                 struct passwd *pw = getpwnam(switchuser);
282                 if (!pw) {
283                         logger(LOG_ERR, _("unknown user `%s'"), switchuser);
284                         return false;
285                 }
286                 uid = pw->pw_uid;
287                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
288                     setgid(pw->pw_gid) != 0) {
289                         logger(LOG_ERR, _("System call `%s' failed: %s"),
290                                "initgroups", strerror(errno));
291                         return false;
292                 }
293                 endgrent();
294                 endpwent();
295         }
296         if (do_chroot) {
297                 tzset();        /* for proper timestamps in logs */
298                 if (chroot(confbase) != 0 || chdir("/") != 0) {
299                         logger(LOG_ERR, _("System call `%s' failed: %s"),
300                                "chroot", strerror(errno));
301                         return false;
302                 }
303                 free(confbase);
304                 confbase = xstrdup("");
305         }
306         if (switchuser)
307                 if (setuid(uid) != 0) {
308                         logger(LOG_ERR, _("System call `%s' failed: %s"),
309                                "setuid", strerror(errno));
310                         return false;
311                 }
312 #endif
313         return true;
314 }
315
316 #ifdef HAVE_MINGW
317 # define setpriority(level) SetPriorityClass(GetCurrentProcess(), level);
318 #else
319 # define NORMAL_PRIORITY_CLASS 0
320 # define BELOW_NORMAL_PRIORITY_CLASS 10
321 # define HIGH_PRIORITY_CLASS -10
322 # define setpriority(level) nice(level)
323 #endif
324
325 int main(int argc, char **argv)
326 {
327         program_name = argv[0];
328
329         setlocale(LC_ALL, "");
330         bindtextdomain(PACKAGE, LOCALEDIR);
331         textdomain(PACKAGE);
332
333         if(!parse_options(argc, argv))
334                 return 1;
335         
336         make_names();
337
338         if(show_version) {
339                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
340                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
341                 printf(_("Copyright (C) 1998-2009 Ivo Timmermans, Guus Sliepen and others.\n"
342                                 "See the AUTHORS file for a complete list.\n\n"
343                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
344                                 "and you are welcome to redistribute it under certain conditions;\n"
345                                 "see the file COPYING for details.\n"));
346
347                 return 0;
348         }
349
350         if(show_help) {
351                 usage(false);
352                 return 0;
353         }
354
355         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
356
357         if(!event_init()) {
358                 logger(LOG_ERR, _("Error initializing libevent!"));
359                 return 1;
360         }
361
362         if(!init_control())
363                 return 1;
364
365         g_argv = argv;
366
367         init_configuration(&config_tree);
368
369         /* Slllluuuuuuurrrrp! */
370
371         srand(time(NULL));
372         crypto_init();
373
374         if(!read_server_config())
375                 return 1;
376
377         if(lzo_init() != LZO_E_OK) {
378                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
379                 return 1;
380         }
381
382 #ifdef HAVE_MINGW
383         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
384                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
385                 return 1;
386         }
387
388         if(!do_detach || !init_service())
389                 return main2(argc, argv);
390         else
391                 return 1;
392 }
393
394 int main2(int argc, char **argv)
395 {
396 #endif
397
398         if(!detach())
399                 return 1;
400
401 #ifdef HAVE_MLOCKALL
402         /* Lock all pages into memory if requested.
403          * This has to be done after daemon()/fork() so it works for child.
404          * No need to do that in parent as it's very short-lived. */
405         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
406                 logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
407                    strerror(errno));
408                 return 1;
409         }
410 #endif
411
412         /* Setup sockets and open device. */
413
414         if(!setup_network())
415                 goto end;
416
417         /* Initiate all outgoing connections. */
418
419         try_outgoing_connections();
420
421         /* Change process priority */
422
423         char *priority = 0;
424
425         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
426                 if(!strcasecmp(priority, "Normal"))
427                         setpriority(NORMAL_PRIORITY_CLASS);
428                 else if(!strcasecmp(priority, "Low"))
429                         setpriority(BELOW_NORMAL_PRIORITY_CLASS);
430                 else if(!strcasecmp(priority, "High"))
431                         setpriority(HIGH_PRIORITY_CLASS);
432                 else {
433                         logger(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         status = main_loop();
445
446         /* Shutdown properly. */
447
448         ifdebug(CONNECTIONS)
449                 dump_device_stats();
450
451         close_network_connections();
452
453 end:
454         logger(LOG_NOTICE, _("Terminating"));
455
456 #ifndef HAVE_MINGW
457         exit_control();
458 #endif
459
460         crypto_exit();
461
462         exit_configuration(&config_tree);
463         free_names();
464
465         return status;
466 }