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