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