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