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