Use our own port when connecting to ourself.
[oweals/tinc.git] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2003 Ivo Timmermans <ivo@o2w.nl>
4                   2000-2003 Guus Sliepen <guus@sliepen.eu.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: tincd.c,v 1.10.4.83 2003/08/03 09:55:20 guus Exp $
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 <openssl/rand.h>
35 #include <openssl/rsa.h>
36 #include <openssl/pem.h>
37 #include <openssl/evp.h>
38
39 #include <lzo1x.h>
40
41 #include <getopt.h>
42
43 #include "conf.h"
44 #include "device.h"
45 #include "logger.h"
46 #include "net.h"
47 #include "netutl.h"
48 #include "process.h"
49 #include "protocol.h"
50 #include "utils.h"
51 #include "xalloc.h"
52
53 /* The name this program was run with. */
54 char *program_name = NULL;
55
56 /* If nonzero, display usage information and exit. */
57 bool show_help = false;
58
59 /* If nonzero, print the version on standard output and exit.  */
60 bool show_version = false;
61
62 /* If nonzero, it will attempt to kill a running tincd and exit. */
63 int kill_tincd = 0;
64
65 /* If nonzero, generate public/private keypair for this host/net. */
66 int generate_keys = 0;
67
68 /* If nonzero, use null ciphers and skip all key exchanges. */
69 bool bypass_security = false;
70
71 /* If nonzero, disable swapping for this process. */
72 bool do_mlock = false;
73
74 /* If nonzero, write log entries to a separate file. */
75 bool use_logfile = false;
76
77 char *identname = NULL;                         /* program name for syslog */
78 char *pidfilename = NULL;                       /* pid file location */
79 char *logfilename = NULL;                       /* log file location */
80 char **g_argv;                                  /* a copy of the cmdline arguments */
81
82 static int status;
83
84 static struct option const long_options[] = {
85         {"config", required_argument, NULL, 'c'},
86         {"kill", optional_argument, NULL, 'k'},
87         {"net", required_argument, NULL, 'n'},
88         {"help", no_argument, NULL, 1},
89         {"version", no_argument, NULL, 2},
90         {"no-detach", no_argument, NULL, 'D'},
91         {"generate-keys", optional_argument, NULL, 'K'},
92         {"debug", optional_argument, NULL, 'd'},
93         {"bypass-security", no_argument, NULL, 3},
94         {"mlock", no_argument, NULL, 'L'},
95         {"logfile", optional_argument, NULL, 4},
96         {"pidfile", required_argument, NULL, 5},
97         {NULL, 0, NULL, 0}
98 };
99
100 #ifdef HAVE_MINGW
101 static struct WSAData wsa_state;
102 #endif
103
104 static void usage(bool status)
105 {
106         if(status)
107                 fprintf(stderr, _("Try `%s --help\' for more information.\n"),
108                                 program_name);
109         else {
110                 printf(_("Usage: %s [option]...\n\n"), program_name);
111                 printf(_("  -c, --config=DIR           Read configuration options from DIR.\n"
112                                 "  -D, --no-detach            Don't fork and detach.\n"
113                                 "  -d, --debug[=LEVEL]        Increase debug level or set it to LEVEL.\n"
114                                 "  -k, --kill[=SIGNAL]        Attempt to kill a running tincd and exit.\n"
115                                 "  -n, --net=NETNAME          Connect to net NETNAME.\n"
116                                 "  -K, --generate-keys[=BITS] Generate public/private RSA keypair.\n"
117                                 "  -L, --mlock                Lock tinc into main memory.\n"
118                                 "      --logfile[=FILENAME]   Write log entries to a logfile.\n"
119                                 "      --pidfile=FILENAME     Write PID to FILENAME.\n"
120                                 "      --help                 Display this help and exit.\n"
121                                 "      --version              Output version information and exit.\n\n"));
122                 printf(_("Report bugs to tinc@nl.linux.org.\n"));
123         }
124 }
125
126 static bool parse_options(int argc, char **argv)
127 {
128         int r;
129         int option_index = 0;
130
131         while((r = getopt_long(argc, argv, "c:DLd::k::n:K::", long_options, &option_index)) != EOF) {
132                 switch (r) {
133                         case 0:                         /* long option */
134                                 break;
135
136                         case 'c':                               /* config file */
137                                 confbase = xstrdup(optarg);
138                                 break;
139
140                         case 'D':                               /* no detach */
141                                 do_detach = false;
142                                 break;
143
144                         case 'L':                               /* no detach */
145                                 do_mlock = true;
146                                 break;
147
148                         case 'd':                               /* inc debug level */
149                                 if(optarg)
150                                         debug_level = atoi(optarg);
151                                 else
152                                         debug_level++;
153                                 break;
154
155                         case 'k':                               /* kill old tincds */
156 #ifndef HAVE_MINGW
157                                 if(optarg) {
158                                         if(!strcasecmp(optarg, "HUP"))
159                                                 kill_tincd = SIGHUP;
160                                         else if(!strcasecmp(optarg, "TERM"))
161                                                 kill_tincd = SIGTERM;
162                                         else if(!strcasecmp(optarg, "KILL"))
163                                                 kill_tincd = SIGKILL;
164                                         else if(!strcasecmp(optarg, "USR1"))
165                                                 kill_tincd = SIGUSR1;
166                                         else if(!strcasecmp(optarg, "USR2"))
167                                                 kill_tincd = SIGUSR2;
168                                         else if(!strcasecmp(optarg, "WINCH"))
169                                                 kill_tincd = SIGWINCH;
170                                         else if(!strcasecmp(optarg, "INT"))
171                                                 kill_tincd = SIGINT;
172                                         else if(!strcasecmp(optarg, "ALRM"))
173                                                 kill_tincd = SIGALRM;
174                                         else {
175                                                 kill_tincd = atoi(optarg);
176
177                                                 if(!kill_tincd) {
178                                                         fprintf(stderr, _("Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n"),
179                                                                         optarg);
180                                                         usage(true);
181                                                         return false;
182                                                 }
183                                         }
184                                 } else
185                                         kill_tincd = SIGTERM;
186 #else
187                                         kill_tincd = 1;
188 #endif
189                                 break;
190
191                         case 'n':                               /* net name given */
192                                 netname = xstrdup(optarg);
193                                 break;
194
195                         case 'K':                               /* generate public/private keypair */
196                                 if(optarg) {
197                                         generate_keys = atoi(optarg);
198
199                                         if(generate_keys < 512) {
200                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
201                                                                 optarg);
202                                                 usage(true);
203                                                 return false;
204                                         }
205
206                                         generate_keys &= ~7;    /* Round it to bytes */
207                                 } else
208                                         generate_keys = 1024;
209                                 break;
210
211                         case 1:                                 /* show help */
212                                 show_help = true;
213                                 break;
214
215                         case 2:                                 /* show version */
216                                 show_version = true;
217                                 break;
218
219                         case 3:                                 /* bypass security */
220                                 bypass_security = true;
221                                 break;
222
223                         case 4:                                 /* write log entries to a file */
224                                 use_logfile = true;
225                                 if(optarg)
226                                         logfilename = xstrdup(optarg);
227                                 break;
228
229                         case 5:                                 /* write PID to a file */
230                                 pidfilename = xstrdup(optarg);
231                                 break;
232
233                         case '?':
234                                 usage(true);
235                                 return false;
236
237                         default:
238                                 break;
239                 }
240         }
241
242         return true;
243 }
244
245 /* This function prettyprints the key generation process */
246
247 static void indicator(int a, int b, void *p)
248 {
249         switch (a) {
250                 case 0:
251                         fprintf(stderr, ".");
252                         break;
253
254                 case 1:
255                         fprintf(stderr, "+");
256                         break;
257
258                 case 2:
259                         fprintf(stderr, "-");
260                         break;
261
262                 case 3:
263                         switch (b) {
264                                 case 0:
265                                         fprintf(stderr, " p\n");
266                                         break;
267
268                                 case 1:
269                                         fprintf(stderr, " q\n");
270                                         break;
271
272                                 default:
273                                         fprintf(stderr, "?");
274                         }
275                         break;
276
277                 default:
278                         fprintf(stderr, "?");
279         }
280 }
281
282 /*
283   Generate a public/private RSA keypair, and ask for a file to store
284   them in.
285 */
286 static bool keygen(int bits)
287 {
288         RSA *rsa_key;
289         FILE *f;
290         char *name = NULL;
291         char *filename;
292
293         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
294         rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
295
296         if(!rsa_key) {
297                 fprintf(stderr, _("Error during key generation!\n"));
298                 return false;
299         } else
300                 fprintf(stderr, _("Done.\n"));
301
302         asprintf(&filename, "%s/rsa_key.priv", confbase);
303         f = ask_and_safe_open(filename, _("private RSA key"), true, "a");
304
305         if(!f)
306                 return false;
307
308         if(ftell(f))
309                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
310
311         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
312         fclose(f);
313         free(filename);
314
315         get_config_string(lookup_config(config_tree, "Name"), &name);
316
317         if(name)
318                 asprintf(&filename, "%s/hosts/%s", confbase, name);
319         else
320                 asprintf(&filename, "%s/rsa_key.pub", confbase);
321
322         f = ask_and_safe_open(filename, _("public RSA key"), false, "a");
323
324         if(!f)
325                 return false;
326
327         if(ftell(f))
328                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
329
330         PEM_write_RSAPublicKey(f, rsa_key);
331         fclose(f);
332         free(filename);
333
334         return true;
335 }
336
337 /*
338   Set all files and paths according to netname
339 */
340 static void make_names(void)
341 {
342         if(netname)
343                 asprintf(&identname, "tinc.%s", netname);
344         else
345                 identname = xstrdup("tinc");
346
347         if(!pidfilename)
348                 asprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
349
350         if(!logfilename)
351                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
352
353         if(netname) {
354                 if(!confbase)
355                         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
356                 else
357                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
358         } else {
359                 if(!confbase)
360                         asprintf(&confbase, "%s/tinc", CONFDIR);
361         }
362 }
363
364 int main(int argc, char **argv)
365 {
366         program_name = argv[0];
367
368         setlocale(LC_ALL, "");
369         bindtextdomain(PACKAGE, LOCALEDIR);
370         textdomain(PACKAGE);
371
372         if(!parse_options(argc, argv))
373                 return 1;
374         
375         make_names();
376
377         if(show_version) {
378                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
379                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
380                 printf(_("Copyright (C) 1998-2003 Ivo Timmermans, Guus Sliepen and others.\n"
381                                 "See the AUTHORS file for a complete list.\n\n"
382                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
383                                 "and you are welcome to redistribute it under certain conditions;\n"
384                                 "see the file COPYING for details.\n"));
385
386                 return 0;
387         }
388
389         if(show_help) {
390                 usage(false);
391                 return 0;
392         }
393
394         if(kill_tincd)
395                 return !kill_other(kill_tincd);
396
397         openlogger("tinc", LOGMODE_STDERR);
398
399         /* Lock all pages into memory if requested */
400
401         if(do_mlock)
402 #ifdef HAVE_MLOCKALL
403                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
404                         logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
405                                    strerror(errno));
406 #else
407         {
408                 logger(LOG_ERR, _("mlockall() not supported on this platform!"));
409 #endif
410                 return -1;
411         }
412
413         g_argv = argv;
414
415         init_configuration(&config_tree);
416
417         /* Slllluuuuuuurrrrp! */
418
419         RAND_load_file("/dev/urandom", 1024);
420
421         OpenSSL_add_all_algorithms();
422
423         if(generate_keys) {
424                 read_server_config();
425                 return !keygen(generate_keys);
426         }
427
428         if(!read_server_config())
429                 return 1;
430
431         if(lzo_init() != LZO_E_OK) {
432                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
433                 return 1;
434         }
435
436 #ifdef HAVE_MINGW
437         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
438                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
439                 return 1;
440         }
441
442         if(!do_detach || !init_service())
443                 return main2(argc, argv);
444         else
445                 return 1;
446 }
447
448 int main2(int argc, char **argv)
449 {
450 #endif
451
452         if(!detach())
453                 return 1;
454                 
455
456         /* Setup sockets and open device. If it doesn't work, don't give up but try again. */
457
458         while(!setup_network_connections()) {
459                 if(do_detach) {
460                         logger(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
461                         sleep(maxtimeout);
462                 } else {
463                         logger(LOG_ERR, _("Not restarting."));
464                         return 1;
465                 }
466         }
467
468         /* Start main loop. It only exits when tinc is killed. */
469
470         status = main_loop();
471
472         /* Shutdown properly. */
473
474         close_network_connections();
475
476         ifdebug(CONNECTIONS)
477                 dump_device_stats();
478
479         logger(LOG_NOTICE, _("Terminating"));
480         return status;
481 }