No C99 initialisers, gcc 2.95.3 doesn't like it.
[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.79 2003/07/30 11:50:45 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 char **environment;                             /* A pointer to the environment on startup */
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         exit(status);
124 }
125
126 static void parse_options(int argc, char **argv, char **envp)
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                                                 }
182                                         }
183                                 } else
184                                         kill_tincd = SIGTERM;
185 #endif
186                                 break;
187
188                         case 'n':                               /* net name given */
189                                 netname = xstrdup(optarg);
190                                 break;
191
192                         case 'K':                               /* generate public/private keypair */
193                                 if(optarg) {
194                                         generate_keys = atoi(optarg);
195
196                                         if(generate_keys < 512) {
197                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
198                                                                 optarg);
199                                                 usage(true);
200                                         }
201
202                                         generate_keys &= ~7;    /* Round it to bytes */
203                                 } else
204                                         generate_keys = 1024;
205                                 break;
206
207                         case 1:                                 /* show help */
208                                 show_help = true;
209                                 break;
210
211                         case 2:                                 /* show version */
212                                 show_version = true;
213                                 break;
214
215                         case 3:                                 /* bypass security */
216                                 bypass_security = true;
217                                 break;
218
219                         case 4:                                 /* write log entries to a file */
220                                 use_logfile = true;
221                                 if(optarg)
222                                         logfilename = xstrdup(optarg);
223                                 break;
224
225                         case 5:                                 /* write PID to a file */
226                                 pidfilename = xstrdup(optarg);
227                                 break;
228
229                         case '?':
230                                 usage(true);
231
232                         default:
233                                 break;
234                 }
235         }
236 }
237
238 /* This function prettyprints the key generation process */
239
240 static void indicator(int a, int b, void *p)
241 {
242         switch (a) {
243                 case 0:
244                         fprintf(stderr, ".");
245                         break;
246
247                 case 1:
248                         fprintf(stderr, "+");
249                         break;
250
251                 case 2:
252                         fprintf(stderr, "-");
253                         break;
254
255                 case 3:
256                         switch (b) {
257                                 case 0:
258                                         fprintf(stderr, " p\n");
259                                         break;
260
261                                 case 1:
262                                         fprintf(stderr, " q\n");
263                                         break;
264
265                                 default:
266                                         fprintf(stderr, "?");
267                         }
268                         break;
269
270                 default:
271                         fprintf(stderr, "?");
272         }
273 }
274
275 /*
276   Generate a public/private RSA keypair, and ask for a file to store
277   them in.
278 */
279 static bool keygen(int bits)
280 {
281         RSA *rsa_key;
282         FILE *f;
283         char *name = NULL;
284         char *filename;
285
286         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
287         rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
288
289         if(!rsa_key) {
290                 fprintf(stderr, _("Error during key generation!\n"));
291                 return false;
292         } else
293                 fprintf(stderr, _("Done.\n"));
294
295         asprintf(&filename, "%s/rsa_key.priv", confbase);
296         f = ask_and_safe_open(filename, _("private RSA key"), true, "a");
297
298         if(!f)
299                 return false;
300
301         if(ftell(f))
302                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
303
304         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
305         fclose(f);
306         free(filename);
307
308         get_config_string(lookup_config(config_tree, "Name"), &name);
309
310         if(name)
311                 asprintf(&filename, "%s/hosts/%s", confbase, name);
312         else
313                 asprintf(&filename, "%s/rsa_key.pub", confbase);
314
315         f = ask_and_safe_open(filename, _("public RSA key"), false, "a");
316
317         if(!f)
318                 return false;
319
320         if(ftell(f))
321                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
322
323         PEM_write_RSAPublicKey(f, rsa_key);
324         fclose(f);
325         free(filename);
326
327         return true;
328 }
329
330 /*
331   Set all files and paths according to netname
332 */
333 static void make_names(void)
334 {
335         if(netname)
336                 asprintf(&identname, "tinc.%s", netname);
337         else
338                 identname = xstrdup("tinc");
339
340         if(!pidfilename)
341                 asprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
342
343         if(!logfilename)
344                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
345
346         if(netname) {
347                 if(!confbase)
348                         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
349                 else
350                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
351         } else {
352                 if(!confbase)
353                         asprintf(&confbase, "%s/tinc", CONFDIR);
354         }
355 }
356
357 int main(int argc, char **argv, char **envp)
358 {
359         program_name = argv[0];
360
361         setlocale(LC_ALL, "");
362         bindtextdomain(PACKAGE, LOCALEDIR);
363         textdomain(PACKAGE);
364
365         environment = envp;
366         parse_options(argc, argv, envp);
367         make_names();
368
369         if(show_version) {
370                 printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE,
371                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
372                 printf(_("Copyright (C) 1998-2003 Ivo Timmermans, Guus Sliepen and others.\n"
373                                 "See the AUTHORS file for a complete list.\n\n"
374                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
375                                 "and you are welcome to redistribute it under certain conditions;\n"
376                                 "see the file COPYING for details.\n"));
377
378                 return 0;
379         }
380
381         if(show_help)
382                 usage(false);
383
384         if(kill_tincd)
385                 exit(!kill_other(kill_tincd));
386
387         openlogger("tinc", LOGMODE_STDERR);
388
389         /* Lock all pages into memory if requested */
390
391         if(do_mlock)
392 #ifdef HAVE_MLOCKALL
393                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
394                         logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
395                                    strerror(errno));
396 #else
397         {
398                 logger(LOG_ERR, _("mlockall() not supported on this platform!"));
399 #endif
400                 return -1;
401         }
402
403         g_argv = argv;
404
405         init_configuration(&config_tree);
406
407         /* Slllluuuuuuurrrrp! */
408
409         RAND_load_file("/dev/urandom", 1024);
410
411         OpenSSL_add_all_algorithms();
412
413         if(generate_keys) {
414                 read_server_config();
415                 exit(!keygen(generate_keys));
416         }
417
418         if(!read_server_config())
419                 exit(1);
420
421         if(lzo_init() != LZO_E_OK) {
422                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
423                 exit(1);
424         }
425
426 #ifdef HAVE_MINGW
427         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
428                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", strerror(errno));
429                 exit(1);
430         }
431 #endif
432         
433         if(!detach())
434                 exit(1);
435                 
436         for(;;) {
437                 if(setup_network_connections()) {
438                         main_loop();
439                         cleanup_and_exit(1);
440                 }
441
442                 logger(LOG_ERR, _("Unrecoverable error"));
443                 cp_trace();
444
445                 if(do_detach) {
446                         logger(LOG_NOTICE, _("Restarting in %d seconds!"), maxtimeout);
447                         sleep(maxtimeout);
448                 } else {
449                         logger(LOG_ERR, _("Not restarting."));
450                         exit(1);
451                 }
452         }
453 }