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