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