Remove pidfile in favour of control socket.
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2007 Guus Sliepen <guus@tinc-vpn.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$
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 #include <openssl/engine.h>
39
40 #include LZO1X_H
41
42 #include <getopt.h>
43
44 #include "conf.h"
45 #include "control.h"
46 #include "device.h"
47 #include "logger.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "process.h"
51 #include "protocol.h"
52 #include "utils.h"
53 #include "xalloc.h"
54
55 /* The name this program was run with. */
56 char *program_name = NULL;
57
58 /* If nonzero, display usage information and exit. */
59 bool show_help = false;
60
61 /* If nonzero, print the version on standard output and exit.  */
62 bool show_version = false;
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 *controlsocketname = NULL;                 /* control socket location */
78 char *logfilename = NULL;                       /* log file location */
79 char **g_argv;                                  /* a copy of the cmdline arguments */
80
81 static int status;
82
83 static struct option const long_options[] = {
84         {"config", required_argument, NULL, 'c'},
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         {"controlsocket", 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                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
113                                 "  -K, --generate-keys[=BITS]    Generate public/private RSA keypair.\n"
114                                 "  -L, --mlock                   Lock tinc into main memory.\n"
115                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
116                                 "      --controlsocket=FILENAME  Open control socket at FILENAME.\n"
117                                 "      --help                    Display this help and exit.\n"
118                                 "      --version                 Output version information and exit.\n\n"));
119                 printf(_("Report bugs to tinc@tinc-vpn.org.\n"));
120         }
121 }
122
123 static bool parse_options(int argc, char **argv)
124 {
125         int r;
126         int option_index = 0;
127
128         while((r = getopt_long(argc, argv, "c:DLd::n:K::", long_options, &option_index)) != EOF) {
129                 switch (r) {
130                         case 0:                         /* long option */
131                                 break;
132
133                         case 'c':                               /* config file */
134                                 confbase = xstrdup(optarg);
135                                 break;
136
137                         case 'D':                               /* no detach */
138                                 do_detach = false;
139                                 break;
140
141                         case 'L':                               /* no detach */
142                                 do_mlock = true;
143                                 break;
144
145                         case 'd':                               /* inc debug level */
146                                 if(optarg)
147                                         debug_level = atoi(optarg);
148                                 else
149                                         debug_level++;
150                                 break;
151
152                         case 'n':                               /* net name given */
153                                 netname = xstrdup(optarg);
154                                 break;
155
156                         case 'K':                               /* generate public/private keypair */
157                                 if(optarg) {
158                                         generate_keys = atoi(optarg);
159
160                                         if(generate_keys < 512) {
161                                                 fprintf(stderr, _("Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n"),
162                                                                 optarg);
163                                                 usage(true);
164                                                 return false;
165                                         }
166
167                                         generate_keys &= ~7;    /* Round it to bytes */
168                                 } else
169                                         generate_keys = 1024;
170                                 break;
171
172                         case 1:                                 /* show help */
173                                 show_help = true;
174                                 break;
175
176                         case 2:                                 /* show version */
177                                 show_version = true;
178                                 break;
179
180                         case 3:                                 /* bypass security */
181                                 bypass_security = true;
182                                 break;
183
184                         case 4:                                 /* write log entries to a file */
185                                 use_logfile = true;
186                                 if(optarg)
187                                         logfilename = xstrdup(optarg);
188                                 break;
189
190                         case 5:                                 /* open control socket here */
191                                 controlsocketname = xstrdup(optarg);
192                                 break;
193
194                         case '?':
195                                 usage(true);
196                                 return false;
197
198                         default:
199                                 break;
200                 }
201         }
202
203         return true;
204 }
205
206 /* This function prettyprints the key generation process */
207
208 static void indicator(int a, int b, void *p)
209 {
210         switch (a) {
211                 case 0:
212                         fprintf(stderr, ".");
213                         break;
214
215                 case 1:
216                         fprintf(stderr, "+");
217                         break;
218
219                 case 2:
220                         fprintf(stderr, "-");
221                         break;
222
223                 case 3:
224                         switch (b) {
225                                 case 0:
226                                         fprintf(stderr, " p\n");
227                                         break;
228
229                                 case 1:
230                                         fprintf(stderr, " q\n");
231                                         break;
232
233                                 default:
234                                         fprintf(stderr, "?");
235                         }
236                         break;
237
238                 default:
239                         fprintf(stderr, "?");
240         }
241 }
242
243 /*
244   Generate a public/private RSA keypair, and ask for a file to store
245   them in.
246 */
247 static bool keygen(int bits)
248 {
249         RSA *rsa_key;
250         FILE *f;
251         char *name = NULL;
252         char *filename;
253
254         fprintf(stderr, _("Generating %d bits keys:\n"), bits);
255         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
256
257         if(!rsa_key) {
258                 fprintf(stderr, _("Error during key generation!\n"));
259                 return false;
260         } else
261                 fprintf(stderr, _("Done.\n"));
262
263         asprintf(&filename, "%s/rsa_key.priv", confbase);
264         f = ask_and_open(filename, _("private RSA key"), "a");
265
266         if(!f)
267                 return false;
268   
269 #ifdef HAVE_FCHMOD
270         /* Make it unreadable for others. */
271         fchmod(fileno(f), 0600);
272 #endif
273                 
274         if(ftell(f))
275                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
276
277         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
278         fclose(f);
279         free(filename);
280
281         get_config_string(lookup_config(config_tree, "Name"), &name);
282
283         if(name)
284                 asprintf(&filename, "%s/hosts/%s", confbase, name);
285         else
286                 asprintf(&filename, "%s/rsa_key.pub", confbase);
287
288         f = ask_and_open(filename, _("public RSA key"), "a");
289
290         if(!f)
291                 return false;
292
293         if(ftell(f))
294                 fprintf(stderr, _("Appending key to existing contents.\nMake sure only one key is stored in the file.\n"));
295
296         PEM_write_RSAPublicKey(f, rsa_key);
297         fclose(f);
298         free(filename);
299
300         return true;
301 }
302
303 /*
304   Set all files and paths according to netname
305 */
306 static void make_names(void)
307 {
308 #ifdef HAVE_MINGW
309         HKEY key;
310         char installdir[1024] = "";
311         long len = sizeof(installdir);
312 #endif
313
314         if(netname)
315                 asprintf(&identname, "tinc.%s", netname);
316         else
317                 identname = xstrdup("tinc");
318
319 #ifdef HAVE_MINGW
320         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
321                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
322                         if(!logfilename)
323                                 asprintf(&logfilename, "%s/log/%s.log", identname);
324                         if(!confbase) {
325                                 if(netname)
326                                         asprintf(&confbase, "%s/%s", installdir, netname);
327                                 else
328                                         asprintf(&confbase, "%s", installdir);
329                         }
330                 }
331                 RegCloseKey(key);
332                 if(*installdir)
333                         return;
334         }
335 #endif
336
337         if(!controlsocketname)
338                 asprintf(&controlsocketname, LOCALSTATEDIR "/run/%s.control", identname);
339
340         if(!logfilename)
341                 asprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
342
343         if(netname) {
344                 if(!confbase)
345                         asprintf(&confbase, CONFDIR "/tinc/%s", netname);
346                 else
347                         logger(LOG_INFO, _("Both netname and configuration directory given, using the latter..."));
348         } else {
349                 if(!confbase)
350                         asprintf(&confbase, CONFDIR "/tinc");
351         }
352 }
353
354 int main(int argc, char **argv)
355 {
356         program_name = argv[0];
357
358         setlocale(LC_ALL, "");
359         bindtextdomain(PACKAGE, LOCALEDIR);
360         textdomain(PACKAGE);
361
362         if(!parse_options(argc, argv))
363                 return 1;
364         
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-2007 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                 return 0;
382         }
383
384         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
385
386         if(!event_init()) {
387                 logger(LOG_ERR, _("Error initializing libevent!"));
388                 return 1;
389         }
390
391         if(!init_control())
392                 return 1;
393
394         /* Lock all pages into memory if requested */
395
396         if(do_mlock)
397 #ifdef HAVE_MLOCKALL
398                 if(mlockall(MCL_CURRENT | MCL_FUTURE)) {
399                         logger(LOG_ERR, _("System call `%s' failed: %s"), "mlockall",
400                                    strerror(errno));
401 #else
402         {
403                 logger(LOG_ERR, _("mlockall() not supported on this platform!"));
404 #endif
405                 return -1;
406         }
407
408         g_argv = argv;
409
410         init_configuration(&config_tree);
411
412         /* Slllluuuuuuurrrrp! */
413
414         srand(time(NULL));
415         RAND_load_file("/dev/urandom", 1024);
416
417         ENGINE_load_builtin_engines();
418         ENGINE_register_all_complete();
419
420         OpenSSL_add_all_algorithms();
421
422         if(generate_keys) {
423                 read_server_config();
424                 return !keygen(generate_keys);
425         }
426
427         if(!read_server_config())
428                 return 1;
429
430         if(lzo_init() != LZO_E_OK) {
431                 logger(LOG_ERR, _("Error initializing LZO compressor!"));
432                 return 1;
433         }
434
435 #ifdef HAVE_MINGW
436         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
437                 logger(LOG_ERR, _("System call `%s' failed: %s"), "WSAStartup", winerror(GetLastError()));
438                 return 1;
439         }
440
441         if(!do_detach || !init_service())
442                 return main2(argc, argv);
443         else
444                 return 1;
445 }
446
447 int main2(int argc, char **argv)
448 {
449 #endif
450
451         if(!detach())
452                 return 1;
453                 
454
455         /* Setup sockets and open device. */
456
457         if(!setup_network_connections())
458                 goto end;
459
460         /* Start main loop. It only exits when tinc is killed. */
461
462         status = main_loop();
463
464         /* Shutdown properly. */
465
466         close_network_connections();
467
468         ifdebug(CONNECTIONS)
469                 dump_device_stats();
470
471 end:
472         logger(LOG_NOTICE, _("Terminating"));
473
474 #ifndef HAVE_MINGW
475         exit_control();
476 #endif
477
478         EVP_cleanup();
479         
480         return status;
481 }